text stringlengths 37 1.41M |
|---|
'''"""
PROBLEM STATEMENT:-
To build a model to accurately classify a piece of news as REAL or FAKE. Using sklearn, build a TfidfVectorizer
on the provided dataset. Then, initialize a PassiveAggressive Classifier and fit the model. In the end,
the accuracy score and the confusion matrix tell us how well our... |
# <문제> 곱하기 혹은 더하기: 문제 설명
# 각 자리가 숫자로만 이루어진 문자열 S가 주어졌을 때, 왼쪽부터 오른쪽으로 하나씩 모든 숫자를 확인하며
# 숫자 사이에 "x", "+" 연산자를 넣어 결과적으로 만들어질 수 잇는 가장 큰술르 구하는 프로그램을 작성하시오.
# 단, 모든 연산은 왼쪽부터 순서대로 이루어진다.
s = "213"
answer = 0
for i in s:
i = int(i)
if i <= 1 or answer <= 1:
answer += i
else:
answer *= i
print(answe... |
n = int(input())
a = 1
b = 2
c = 3
def hanoi(n, a, b, c):
global count
if n <= 0:
pass
else:
hanoi(n-1, a, c, b)
print(a, c)
hanoi(n-1, b, a, c)
def count(n):
if n == 1:
return n
else:
return count(n-1)*2+1
print(count(n))
hanoi(n, a, b, c)
# n = in... |
# Author: Branden Kim
# Assignment: 5
# Description: Recursive function to print out the echoes of a sentence
def echo_game(word, fraction, num_echoes):
if len(word) > 1:
echo_len = len(word) - int(len(word) * fraction)
print(word)
return echo_game(word[echo_len:], fraction, num_echoes + 1... |
# Author: Branden Kim
# Assignment: 5
# Description: Recursive GCD function
def gcd(first, second, curr_attempt):
if second == 0:
return first
else:
return gcd(second, first % second, first % second)
def main():
while True:
try:
first = int(input('Please enter the fir... |
# -*- coding: utf-8 -*-
"""
Created on Saturday, April 1st 2018
@author: Sagar Kishore
"""
class Stack:
"""
Stack Class that takes in the stack name as mandatory parameter.
"""
def __init__(self, name, **kwargs):
self.name = name
self.words = []
self._rank_dict = {
... |
#Polynomial Regression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the Dataset
dataset = pd.read_csv('Test_data.csv')
X = dataset.iloc[:,4:6].values
y = dataset.iloc[:,8:9].values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import L... |
#Polynomial Regression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the Dataset
dataset = pd.read_csv('Final_file_of_family_data.csv')
X = dataset.iloc[:,[4,9,12,13]].values
y = dataset.iloc[:,8:9].values
#Splittung the data into training and test set
from sklearn.cross_validat... |
def primo (numero):
valor = range(2,numero)
contador = 0
for n in valor:
if numero % n == 0:
contador +=1
print("divisor:", n)
if contador > 0 :
return False
else:
return True
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Решить поставленную задачу:
написать функцию, вычисляющую среднее гармоническое
своих аргументов a1, a2, ... an
Если функции передается пустой список аргументов,
то она должна возвращать значение None
"""
def average(*x):
"""Поиск среднего гармонического"""
... |
#괄호 맞추기
#(())() -> True
#())()(()) -> False
"""왼쪽 괄호는 자기 짝인 오른쪽 괄호가 올때까지 기다려야한다. 왼쪽 괄호를 Stack에 저장하여 짝이 맞는
오른쪽 괄호가 나올때까지 저장해둔다."""
# 1. Stack 객체를 사용해야 하므로 Stack 클래스를 만든다.
class Stack:
# 생성 함수
def __init__(self):
self.li = []
# Stack에 val 추가 함수
def push(self, val):
self.li.appe... |
import os
p = 'insert path of the directory you want to index' #path to explore
t = 'target directory to store the index in' #folder to store the index file in
filename = 'index.txt' #name of index file
#i is step of indentation
def makeline(txt, i):
ind = " " * i
txt = ind + txt
return txt
#i i... |
# -*- coding: utf-8 -*-
"""
:mod:`test` module : test module for experiences assignment
:author: `FIL - IEEA - Univ. Lille1.fr <http://portail.fil.univ-lille1.fr>`_
:date: 2015, december
"""
import sys
import experience
import sorting
def compare (m1,m2):
return experience.compare(m1,m2)
# STRATEGY 1
def neg... |
#!/usr/bin/env python3
"""
:author: Vienne & Lecornet
:date: 20/09/16
:object: representation of numbers
"""
def integer_to_digit(entier):
"""
Parameters: integer (int) –
Returns: the character representing the hexadecimal digit
Return type: str
CU: integer >= 0 and integer < 16
"""
asser... |
p=input()
q=p[::-1]
if p==q:
print("palidrom")
else:
print("not Palidorm")
|
import itertools
a=[1,2,3,4,5,6,7,8,9]
for i in range(1,len(a)):
b=list(itertools.combinations(a,i))
for j in range(len(b)):
print(a.index(8))
|
n=7;
for i in range(0,n):
if i==(n//2):
print("x"*n,end=" ")
else:
for j in range(0,n):
if j==(n//2):
print("x",end=" ")
else :
print(" ",end="")
print()
|
approve = input("Are you ready to use my program? ")
approve_list = ["yeah", "yes", "yh", "y"]
if approve in approve_list:
print("Welcome!, this is a simple python program!")
name = input("What is your name: ")
age = int(input("How old are you?: "))
day = age * 365
hour = day * 24
minute = hour * 60
names = ["... |
# Write a function that takes in a string of one or more words, and returns the same string,
# but with all five or more letter words reversed (Just like the name of this Kata).
#Strings passed in will consist of only letters and spaces.
#Spaces will be included only when more than one word is present.
# Examples: ... |
import random
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
lengthOfNames=len(names)
print(lengthOfNames)
r=random.randint(0,lengthOfNames-1)
print(f"... |
# A simple sequential search implementation
def sequential_search(l, search_item):
position = 0
for i in l:
if i == search_item:
return position
position += 1
return 'Not Found'
print(sequential_search([1, 5, 7, 8, 23, 4543], 1))
# A sequential search taking advantage of a s... |
import time
numbers = [23 , 1999, -23333, 1, 0, 675, 90]
def find_minimum_fast(nums):
"""
Finds the minimum number in a list
O(n2)
:param nums:
:return:
"""
smallest = nums[0]
for n in nums:
if n < smallest:
smallest = n
return smallest
def find_minimum_slow(n... |
# The Divide by 2 algorithm assumes that we start with an integer greater than 0. A simple iteration then
# continually divides the decimal number by 2 and keeps track of the remainder. The first division by 2 gives
# information as to whether the value is even or odd. An even value will have a remainder of 0.
# It wil... |
import random
from queue import Queue
# The Printer class will need to track whether it has a current
# task. If it does, then it is busy and the amount of time
# needed can be computed from the number of pages in the task. The
# constructor will also allow the pages-per-minute setting to be initialized.
# The tick m... |
# 二叉搜索树或二叉排序树、二叉查找树
"""
一颗二叉树,可以为空;如果不为空,则:
1:非空左子树的所有键值小于其根节点的键值
2:非空右子树的所有键值大于其根节点的键值
3:左、右子树都是二叉搜索树
Position Find
Position FindMin
Position FindMax
该页面除了第一个搜索测试没问题之后,后续应该都有错误
"""
class Node(object):
"""节点类"""
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchil... |
def sumodd():
x=int(input())
y=int(input())
s=x+y
if s%2==0:
print('even')
else :
print('odd')
try:
sumodd()
except:
print('invalid')
|
n=float(input("Enter any decimal value:"))
if(n<0):
a=int(n-0.5)
else:
a=int(n+0.5)
print(a);
|
def greet_user():
"""this is a docstring, something that describe the function."""
print("Hello!!!")
greet_user() # this is how we Call function
def greet_user_by_name(name): # (name) is requared parameter
"""it will say hello and use the name entered."""
print(f"Hello, {name.title()}!")
greet_user_by... |
class User:
login_attempts = 0
def __init__(self):
pass # pass means do nothing, it is just place holder
### self.login_attempts = 0 this is the alternative way of creating global variable
def increment_login_attempt(self):
print("incrementing the value by 1 ...")
self.login... |
# tabular data manipulation
import numpy as np
import pandas as pd
# datetime utilities
from datetime import timedelta, datetime
import datetime
# visualization
import matplotlib.pyplot as plt
# no yelling in the library
import warnings
warnings.filterwarnings("ignore")
def drop_cols(df):
'''
Takes in df ... |
print("Introduce el valor del radio: ")
rRadio = float(input())
print("Introduce el angulo: ")
rAngulo = float(input())
rVolumen = float(3) / 4 * (3.1416 * rRadio ** 3 / 360 * rAngulo)
print("El volumen de la cuña es: ", end='', flush=True)
print(rVolumen, end='', flush=True)
|
import math
def sum_of_primes(limit):
# This function finds the sum of all the prime numbers below the limit.
count = limit
total = 2
# If the input limit is even, it's stepped down to the next odd.
if count % 2 == 0:
count -= 1
# The while loop moves the count down from t... |
'''
1. Palindrome(n)
Write a recursive function that iteratively calculates whether a sequence is a palindrome
(the same forwards as backwards). You need to explicitly highlight the base case
and recursive case in your comments (marks will be heavily weighted towards this).
'''
import math #importing the math function... |
import copy
dictionary = {'key1': 'value1', 'key2': 'value2'}
dictionary['key3'] = 'value3'
print(dictionary)
print(dictionary['key1'])
d1 = dict(key1='val1', key2='val2')
print(d1)
d2 = {
'str': 'string as key',
12345: 'int as key',
(1, 2, 3): 'tuple as key'
}
print(d2)
print(d2[(1, 2, 3)])
# check key... |
cup_str = input('Введите количество чашек ') # age_str это строка
cup = int(cup_str) # age это int
cup_bonus = int(cup / 6)
print(cup_bonus)
|
#Code written by Farbod Kamiab
#The code reads GPS data from the New York City Taxi & Limousine Commission (NYCT&L) data on taxi trips and plots the GPS points on a map of New York City.
import numpy as np
import pandas as pd
import matplotlib.pyplot as pl
import pygmaps #One needs to install pygmaps to run this code... |
import sqlite3
dataFile = 'data/data.db'
defaultData = 'data/default_data.txt'
def init():
conn = sqlite3.connect(dataFile)
cursor = conn.cursor()
cursor.execute('CREATE TABLE soul (id INTEGER PRIMARY KEY AUTOINCREMENT, text VARCHAR(1024))')
try:
with open(defaultData, 'r', encoding='UTF-8') as f:
l... |
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
sum = int(num1) + int(num2)
print('The sum of {0} + {1} is {2}'.format(num1, num2, sum))
|
# Automatic Sebastian game player
# B551 Fall 2020
#
# Based on skeleton code by D. Crandall
#
#
# This is the file you should modify to create your new smart player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice object which records the
#... |
import sqlite3
conn = sqlite3.connect('answers.db') # You can create a new database by changing the name within the quotes
c = conn.cursor() # The database will be saved in the location where your 'py' file is saved
# Create table - ANSWERS
c.execute('''CREATE TABLE ANSWERS
([generated_id] INTEGER PRIMA... |
import re
class Phone(object):
def __init__(self, phone_number):
self.number=phone_number
parse_number=re.sub(r'^(\+1)|[()-. ]',"",self.number)
if (parse_number[0]=="1" and len(parse_number)==11):
parse_number=re.sub(r'^1',"",parse_number)
if len(parse_number)>10 or parse... |
NODE, EDGE, ATTR = range(3)
from collections import defaultdict
class Node(object):
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge(object):
def __init__(self, sr... |
"""
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a... |
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def get_length(list):
# determine length of the list
length_list = 0
current_node = list
current_node2 = list.next
while current_node != None and current_node != current_node2:
current_node = current_n... |
# создай список с целыми числами произвольных значений произвольной длины,
# отсортируй его по возрастанию и убыванию, запиши результат в отдельные переменные
datas = [10, 45, 165, 1834, 23, 57, 4]
minmax = sorted(datas)
maxmin = sorted(datas, reverse=True)
# даны два списка с числами, нужно вернуть список, который со... |
import sqlite3 #enable control of an sqlite database
DB_FILE="ultimate.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
#######################################
# USERS TABLE
# TABLE BREAKDOWN
# 1 BLOCK = identification to connect d... |
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Created on Jan 24, 2014
@author: So... |
'''
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the t... |
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Created on Jan 12, 2014
@author: Songfan
'''
''' thought: two pointer track from the back '''
def addBinary(a, b):
assert(isinstance(a,str) and isinstance(b,str)), 'input error'
na = len(a)
... |
'''
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
able to handle dups
Created on Jan 12, 2014
@author: Songfan
'''
'''
recursion + memoization
recursively add the last elemen... |
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Cr... |
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Created on Jan 12, 2014
@author: Songfan
'''
''' algorithm: reuse merge 2 sorted list, O(n1+n2+...+nk) time. O(1) space '''
from LC_mergeTwoSortedList import mergeList, ListNode, LinkedList
def mergeKList(lists... |
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Created on Jan 2, 2014
@author: Songfan
'''
''' thought: two pointer from begin and end, meet together ... |
'''
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has le... |
'''
Linear time selection
select the k-th largest
Created on Apr 5, 2014
@author: Songfan
'''
import timeit
# def by_med(A):
# A.sort()
# return A[len(A)//2]
#
# def partition(A):
# n = len(A)
# if n < 5:
# pi = by_med(A)
# else:
# ''' median of median as pivot '''
# med... |
'''
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, ... , a... |
'''
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, su... |
'''
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Created on Jan 12, 2014
@author: Songfan
'''
''' thought: two pointer strategy, one is the running pointer, the other i... |
'''
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Created on Feb 1, 2014
@author: Songfan
'''
''' for loop: 1. check rows, 2. check cols, 3. check 3*3 blocks
1 and 2 can be combined
'''
... |
'''
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Created on Jan 2, 2014
@author: Songfan
'''
''' tho... |
'''
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.
Created on Jan 27, 2014
@author: Songfan
'''
''' memoization '''
def minPathSum(Grid):
ro... |
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number... |
'''
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
Created on Jan 30, 2014
@author: Songfan
'''
''' ... |
'''
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Created on Feb 15, 2014
@author: Songfan
'''
''' 1. duplicate each node
2. copy each rand ptr
3. separate the linked list
'''
# Definition ... |
'''
Created on Nov 7, 2013
@author: Songfan
'''
# use list structure to implement Minimum Binary Heap
class MinBinaryHeap:
def __init__(self):
self.heapList = [0]
self.size = 0
def insert(self, item):
self.heapList.append(item)
self.size += 1
self.siftUp(self.... |
'''
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],... |
# Bradley N. Miller, David L. Ranum
# Introduction to Data Structures and Algorithms in Python
# Copyright 2005
#
#stack.py
class Stack:
def __init__(self):
self.data = []
def isEmpty(self):
return self.data == []
def push(self, item):
self.data.append(item)
def pop(self):
... |
'''
print the leaf of a binary tree
Created on Mar 23, 2014
@author: Songfan
'''
class TreeNode:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.val)
class BinaryTree:
def... |
'''
print pascal's triangle, LeetCode, ex: n=3
[
[1]
[1,1]
[1,2,1]
]
Created on Dec 4, 2013
@author: Songfan
'''
def printPascal(result,n):
print'['
for i in range(1,n+1):
spaceNum = n-i+1
startIdx = i*(i-1)/2
endIdx = (i+1)*i/2
data = '['+','.join(result[startIdx:endIdx... |
'''
Created on Dec 12, 2013
@author: Songfan
'''
from linkedList import LinkedList
def insertionSort(head):
if not head or not head.next: return head
head2 = head
curr1 = head.next
head2.next = None
while(curr1):
curr2 = head2
while(curr2):
if curr1.value<curr2.value:
... |
class Person(object):
def __init__(self, name, education, age, uniform):
self.name = name
self.education = education
self.age = age
self.uniform = uniform
def work(self):
print("%s goes to work" % self.name)
class Employee(Person):
def __init__(self, name, educatio... |
import math
def prime_checker():
num_check = int(input("Enter a number: ")) # Takes the input from the user and sets it to the variable num_check
sqr_test = math.sqrt(num_check) # Tests the number by square ro... |
import numpy as np
import math
class LossFunction:
def __init__(self):
self._result = None
def zero_one(self, feature_vector, weight_vector, y):
score = np.dot(feature_vector, weight_vector) # how confident we are in prediction
margin = score * y # how correct weare in prediction
... |
# NFL Fourth Down Statistics
#
#In this code, we will examine the play-by-play data from the 2015 NFL season,
#focusing on the fourth down statistics.
import numpy as np # library for handling arrays
import pandas as pd #library for handling dataframes
import matplotlib.pyplot as plt #library for viewing graphs
... |
"""...
Global variables:
WIDGETS - a mapping from strings to the wx.Window class objects that
they represent
"""
import wx
WIDGETS = {
"Button": wx.Button,
"Slider": wx.Slider,
"Listbox": wx.ListBox
}
class Widget(object):
"""Represents a wx.Window.
Instance variables:
attrs... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 17 14:44:07 2021
@author: manis
"""
#sum of cubes
sum_of_cubes = []
sum_of_cubes= ["i=" + str(i) + " j=" + str(j) + " " + \
str(i**3 + j**3) for i in range(1 , 20) \
for j in range(1 , 20 ) if i <= j and (i**3 + j**3) == 1729 ]
#sum_of_cubes= [ i**3 + ... |
"""
The Parse class takes in a function and
returns the breakdown of the function needed to write a C function.
The bodyList is given to the Formatter class to generate a C-style code.
"""
#Libraries needed
import ast
import inspect
import symtable
#Parser class
class Parser:
#====================================... |
#1q
def listoftuples(11,12):
return list(map(lambda x,y:(x,y),11,12))
list1 = [1,2,3]
list2 = ['a','b','c']
print(list of tuples(list1,list2))
def merge(list1,list2):
merged_list = list(zip(list1,list2))
return merged_list
list1 = [1,2,3]
list2 = ['a','b','c']
print(merge(list1,list2))
#2q
... |
#Comparing Numbers
def max_num(x,y,z):
#Use a comparison operator to print the largest number.
if x >= y and x >= z:
return x
elif y >= x and y >= z:
return y
else:
return z
print(max_num(5,4,3)) |
# functions with/without parameters
# functions that return.
def addition(): # without params
x = 7
y = 8
answer = x + y
print('You total is ', answer)
addition()
addition()
#===================================
# with params
def addition2(x, y):
answer = x + y
print('Your 2nd total is ', ans... |
# Control statements, loops for/while loop
county = str(input('Which are you from?:'))
if county == 'Meru':
print('Bring some bananas')
elif county == 'Mombasa':
print('Bring some coconut')
else:
print('Invalid County') |
# for loop - used to repeat a task n -times
for x in range(1,11, 1): # 2 is the step
print('Its looping ', x)
# lists/tuples
fruits = ('Apple', 'Orange', 'Mango', 'Passion') # tuple
# use a for loop to loop through the fruits
for fruit in fruits:
print(fruit) # prints each fruit
|
"""
This module contains functions designed to split a time series into linear segments by approximating them as straight lines.
This is a common form of time series data compression.
"""
# NOTE: e norm here is NOT standard error: it is length-averaged error
from itertools import chain
import numpy as np
from scipy.... |
############################Problem 1###################################
import pandas as pd
import numpy as np
# Loading the data set
salary_train = pd.read_csv("C:/Users/hp/Desktop/naive bayes assi/SalaryData_Train.csv",encoding = "ISO-8859-1")
salary_test = pd.read_csv("C:/Users/hp/Desktop/naive bayes ass... |
# -*- coding: utf-8 -*-
"""
如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true;否则返回 false。
"""
class Solution:
# one 实现方式和 numsum_#653相同,存入集合中,判断最后集合是否只剩一个元素(True)。
# 执行用时 48ms,内存消耗 13.8MB
# def isUnivalTree(self, root):
# s = set()
# queue = [root]
# while queue:
# ... |
from collections import defaultdict
class Trie:
def __init__(self):
def node():
return defaultdict(node)
self.root = node()
def insert(self, word: str):
node = self.root
for c in word:
node = node[c]
node[None]
def find(self, word: str) ... |
# 8.9 LAB: Car value (classes)
# Complete the Car class by creating an attribute purchase_price (type int) and the method print_info() that outputs the car's information.
#
# Ex: If the input is:
#
# 2011
# 18000
# 2018
# where 2011 is the car's model year, 18000 is the purchase price, and 2018 is the current year, th... |
def find_number(p_array, c_array):
return sorted(p_array[c_array[0] - 1:c_array[1]])[c_array[2] - 1]
def solution(array, commands):
answer = []
for c in commands:
answer.append(find_number(array, c))
return answer |
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
ldx, rdx = 0, len(s) - 1
while (ldx < rdx):
s[ldx], s[rdx] = s[rdx], s[ldx]
ldx += 1
rdx -= 1 |
import pprint #pprint makes the print look cleaner
message = '''adjsajdbnasa
bndsDASDF
S''' #if I use three quotes to open and end a string, I can format it in any way!
count = {}
for character in message.upper():
count.setdefault(character,0) #adds letter seen for the first time as a key and def... |
from collections import Counter
from matplotlib import pyplot as plt
grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
def decile(grade: float) -> int:
return grade // 10 * 10
histogram = Counter(decile(grade) for grade in grades)
# move cada barra para a esquerda em 4
# dá para cada barra sua alt... |
import numpy as np
import matplotlib.pyplot as plt
def drag_force(velocity):
B_m = 0.0039 + 0.0058 / (1. + np.exp((velocity-35)/5))
return B_m * velocity
class BallInAir:
def __init__(self, x0, y0, velocity, angle_deg, noise=[1., 1.]):
self.x = x0
self.y = y0
angle = np.deg2rad(... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head
def add(self, key): #agregar al principio
nodo = Node(key)
if not self.isEmpty():
... |
#vectores
#Crear un programa que reciba 10 números y calcule su suma
i = 0 #contador
suma = 0 #acumulador
while i < 10:
numero = int(input(f"Digite el {i+1} número: "))
suma = suma + numero
i = i + 1
print(f"El valor de la suma es {suma}")
suma = 0
for i in range(0,10,1):
numero = int(input(f"Digi... |
#Paso 1 instalacion de la librería
#Paso 2 importar librería y crear ventana principal y su mainloop()
from tkinter import *
main_window = Tk() #Ventana principal de la aplicación
main_window.title("Formulario de registro")
#main_window.mainloop() #Abre la ventana y entra en un loop que permite tener la ... |
#deque: list-like container with fast appends and pops on either end
#namedtuple: function for creating tuple subclasses with named fields
from collections import deque, namedtuple
#Make the default value for node distance infinity
infinity = float('inf')
#Define a namedtuple 'Edge'
Edge = namedtuple('Edge', 'start, ... |
from datetime import datetime
class MyLogger:
"""
Замеряет скорость работы кода. Результат печатает в консоль и логирует в файл.
"""
def __init__(self, log_file_path):
self.path = log_file_path
def __enter__(self):
self.log = open(self.path, 'a', encoding='utf-8')
self.s... |
from turtle import *
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
x = 0
print(x)
for i in colors:
setx(x)
fillcolor(i)
begin_fill()
pencolor(i)
forward(30)
right(90)
forward(60)
right(90)
forward(30)
right(90)
forward(60)
right(90)
end_fill()
x += 30
... |
from turtle import *
length = 100
num_sides = 3
degrees = [60,30,18,12,8]
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
i = 0
for degree in degrees:
pencolor (colors[i])
left(degree)
for _ in range(num_sides):
forward(length)
right(360/num_sides)
num_sides += 1
i += 1
... |
import os
def rename(path):
filelist = os.listdir(path)
for files in filelist:
Olddir = os.path.join(path, files)
if os.path.isdir(Olddir):
rename(Olddir)
continue
f,p = os.path.splitext(files)
f1,p1 = os.path.splitext(f)
Newdir = os.path.join(path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.