text stringlengths 37 1.41M |
|---|
# coding:utf-8
# 2019-2-1
"""
导致引用计数+1的情况
对象被创建,例如a=23
对象被引用,例如b=a
对象被作为参数,传入到一个函数中,例如func(a)
对象作为一个元素,存储在容器中,例如list1=[a,a]
导致引用计数-1的情况
对象的别名被显式销毁,例如del a
对象的别名被赋予新的对象,例如a=24
一个对象离开它的作用域,例如f函数执行完毕时,func函数中的局部变量(全局变量不会)
对象所在的容器被销毁,或从容器中删除对象
"""
import gc
class A(object):
pass
clas... |
'''
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as... |
# coding=utf-8
import sys
"""
1. We have an integer array where all the elements appear twice while only 1 elements appears once. Please find the 1 elements. [直接说出步骤,然后换成下面这道题]
2. We have an integer array where all the elements appear twice while only 2 elements appears once. Please find the 2 elements.
数组中只有两个数字只出现... |
# 2018-8-16
# 算法导论 P245
"""
压缩原理:统计词频
编码分为:
a. 定长编码
非满二叉树
b. 变长编码
满二叉树,比定长编码节约25%空间
"""
class TreeNode(object):
"""Define a tree"""
def __init__(self, x=None):
self.freq = x
self.left = None
self.right = None
class minQueue(object):
"""
最小优先列队,先进先出。
有待改进。
"""
def __init__(self,n=[]):
self.queu... |
# 2018-8-5 ~ 2018-8-6
# Bucket Sort
# Reference
# Introduction to Algorithms [P112]
# Data Structures and Algorithm Analysis in C [P189]
# https://www.cnblogs.com/shihuc/p/6344406.html
class BucketSort(object):
"""
1. Define the data mapping function f(x) according to the data type
2. Plan the data separa... |
'''
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
'''
# 2018-11-6
# 279. Perfect Squares
# https://leetcode.com/p... |
'''
There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.
Given n online courses represented by pairs (t,d), your tas... |
"""
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[... |
# 2018-9-2
# Binary Indexed Tree
# https://www.hackerearth.com/zh/practice/notes/binary-indexed-tree-made-easy-2/
# 推荐看: https://www.cnblogs.com/whensean/p/6851018.html
# 网页底部有数据结构总览表: https://en.wikipedia.org/wiki/Fenwick_tree
# 来源于LeetCode
# 307. Range Sum Query - Mutable
# Binary Indexed Tree
# 关键在于 k -= (k & -k) ... |
# coding:utf-8
# 2019-2-4
"""建造模式:将产品的内部表象和产品的生成过程分割开来,从而使一个建造过程生成具有不同的内部表象的产品对象。建造模式使得产品内部表象可以独立的变化,客户不必知道产品内部组成的细节。建造模式可以强制实行一种分步骤进行的建造过程
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
角色:
抽象建造者(Builder)
具体建造者(Concrete Builder)
指挥者(Director)
产品(Product)
建造者模式与抽象工厂模式相似,也用来创建复杂对象。主要区别是建造者模式着重一步步构造一个复杂对象,而抽象工厂模式着重于多个系列的产品对象。
... |
'''
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses subst... |
# coding:utf-8
"""给定一个字符串A,一个字符串B,求B在A中出现的次数"""
import sys
def solver(a, b):
ret = 0
lenB = len(b)
lenA = len(a)
if lenA < lenB:
return ret
for i in range(0, lenA - lenB + 1):
cur = a[i:i+lenB]
if cur == b:
ret += 1
return ret
def test():
a, b = "zyz... |
from tkinter import *
from tweet import *
def search():
tweet_list.delete(0,'end')
index = 0
count = input_count.get()
username = input_name.get()
tweets = get_result(username,count).most_common()
for tweet in tweets:
index+=1
tweet_list.insert(index, str(tweet[0])+":"+str(tweet... |
#
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# @lc code=start
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# 在判断m和n时,需要判别m与n的关键性
# nums2的关键点>nums1... |
#
# @lc app=leetcode.cn id=107 lang=python3
#
# [107] 二叉树的层序遍历 II
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[... |
def goroad(road: list, curp: list, direc: int):
left, right = curp[0], curp[1]
if direc == 2:
while right >= 0:
if road[left][right] == '#':
break
right -= 1
return [left, right + 1]
elif direc == 3:
while right < len(road[0]):
if r... |
from sys import exit
def ip_valid(ip):
'''This functions tests if IPv4 address is valid. If yes, it returns IPv4 address.
Function will accepts IP address from classess A, B and C except:
- 127.0.0.0/8 - uses for loopback addresses
- 169.254.0.0/16 - used for link-local addresses'''
ip_octets = ip.split(... |
def bubble_sort(seq):
for i in range(len(seq)):
for j in range(i, len(seq)):
if seq[j] < seq[i]:
tmp = seq[j]
seq[j] = seq[i]
seq[i] = tmp
def selection_sort(seq):
for i in range(len(seq)):
position = i
for j in range(i, le... |
def factorial(n):
if n==1:
return 1
else:
return n * factorial(n-1)
print(factorial(10))
def sum(n):
if n ==1:
return 1
else:
return n +sum(n-1)
def tail_sum(n,accumulator=0):
if n==0:
return accumulator
else:
return tail_sum(n-1, accumulator+n... |
passerby_speech='Hello'
if passerby_speech == 'Hello':
print("Hello how are you ????")
elif passerby_speech=='hi':
print("Hi How are you????")
else:
print("Hey")
"""
Ternary operator demo
"""
me = "Hi" if passerby_speech =='Hi' or passerby_speech=='Hello' else "Hey"
print(me)
a=3
a =7 if 3**3 >9 else... |
print("Today I had {0} cup of {1}".format(3,'Coffee'))
print("prices: {x},{y},{z}".format(x=20,y=40,z=80))
print("The {vehicle} had {0} crashes in {1} months".format(5,6,vehicle='car')) |
class Person:
def __init__(self, pid, x, y, rescue_time):
self.id = pid
self.x = x
self.y = y
self.rescue_time = rescue_time
self.hospital_idx = None
self.hospital_x = None
self.hospital_y = None
def assign_hospital(self, hospital_id, x, y):... |
"""Solutions to Data Manipulation section of 100 DS questions set."""
import numpy as np
def num_to_color(arr):
"""Return array replacing 0's with 'red' and 1's are replaced with 'blue'.
Converts 0's to the string 'red' and 1's to the string 'blue'.
Parameters
----------
arr: numpy array
... |
#Local Search
import sys as sys
import random as rd
def testSolution(sol):
for k in range(len(sol)-1):
for i in range(k+1,len(sol)):
if(sol[k] == sol[i]+(i-k) or sol[k] == sol[i]-(i-k)):
return False
return True
def iterations(sol,n):
for j in range(n):
if(te... |
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__("circle")
self.penup()
self.shapesize(0.5, 0.5)
self.color("red")
self.speed("fastest")
x = random.randint(-14, 14) * 20
y = random.randint(-13, 14) * 20
... |
#goes through list num by num to find the given num
def linearSearch(numlist, numSought):
index = -1
i = 0
found = False
while i < len(numlist) and found == False:
if numlist[i] == numSought:
index = i
found = True
i = i + 1
return index
#test list
numlist = ... |
def insertion_sort(arr):
for i in range(1, len(arr)):
cur_num = arr[i]
j = i - 1
while j >= 0 and cur_num < arr[j]:
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = cur_num
return arr
if __name__ == '__main__':
A = [20, 15, 2, 3, 25, 30, 14, 26, 5, 10, 18, 1]
... |
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
node = Node(data, self.head)
self.head = node
def insert_at_end(self, data):
if self.head is None:
self.head = Node(d... |
# Dynamic Programming Python implementation of Matrix Chain Multiplication
# See the Cormen book for details of the following algorithm
import sys
# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
def MatrixChainOrder(p, n):
# For simplicity of the program, one extra row and one extra column are
# allocate... |
from my_util.graph_util import *
__author__ = 'He Li'
"""
Can modify depth first search to add parenthesis theorem
"""
def depth_first_search(graph):
# 0 stands for white
# 1 stands for gray
# 2 stands for black
color = [0] * len(graph)
pi = [None] * len(graph)
d = [0] * len(graph)
f = ... |
__author__ = 'He Li'
def fib_dp(n):
c = [0 for i in range(n+1)]
c[0] = 0
c[1] = c[2] = 1
for i in range(3, n+1):
c[i] = c[i-1] = c[i-2]
return c[n]
def fib_memoize(n):
c = [0 for i in range(n+1)]
c[0] = 0
c[1] = c[2] = 1
for i in range(3, n+1):
c[i] = -1
... |
import os
import platform
from operator import attrgetter
def clear():
os.system("clear" if platform.system() == "Darwin" else "cls")
class Book():
def __init__(self):
self.ID = -1
self.name = ""
self.author = ""
self.price = -1.0
def setID(self, val):
sel... |
# How to determine if triangle exists.
a,b,c= input('Enter three sides of a triangle: ').split(',')
a=float(a)
b=float(b)
c=float(c)
if (b+c > a) and (a+c > b) and (b+a > c):
print('The triangle exists.')
else:
print("The triangle doesnot exists.")
|
# Number of digits in an Integers.
count = 0
num = int(input('Enter any number: '))
while num > 0:
num = num // 10
count += 1
print('Number of digits:', count) |
# How to create multiplication table using for loop?
x = int(input('Which number multiplication table do you want? '))
for y in range(1,11):
print(x, 'x', y, '=', x * y)
|
# How to create a multiplication table using while loop.
x = int(input('Which number multiplication table do you want? '))
y = 0
while y <= 10:
print(x, 'x', y, '=', x*y)
y = y+1 |
# How to check if a point belongs to a circle?
import math
try:
x, y = [float(s) for s in input('Enter points: ').split(',')]
h, k = [float(s) for s in input('Enter centre point: ').split(',')]
r = float(input('Enter radius of circle: '))
check = math.sqrt((x - h) ** 2 + (y - k) ** 2)
if r == check... |
# How to check for file extension.
exe = ['gif', 'png', 'jpeg', 'jpg', 'txt', 'py']
file_exe = input('Enter you filename: ').split('.')
if len(file_exe) >= 2:
extension = file_exe[-1]
if extension in exe:
print('File extension exists')
else:
print('File extension does not exist')
else:
p... |
# How to reverse number?
word = input('Enter any word:')
rev = word[::-1]
print(rev)
|
# This is a comment. Python will ignore these lines (starting with #) when running
import math as ma
# To use a math function, write "ma." in front of it. Example: ma.sin(3.146)
# These functions will ask you for your number ranges, and assign them to 'x1' and 'x2'
x1 = raw_input('smallest number to check: ')
x2 =... |
import numpy as np
class Knapsack01Problem:
"""This class encapsulates the Knapsack 0-1 Problem from RosettaCode.org
"""
def __init__(self):
# initialize instance variables:
self.items = []
self.maxCapacity = 0
# initialize the data:
self.__initData()
def __l... |
'''Ciphers file'''
import random
import crypto_utils
class Cipher():
'''Cipher class'''
def __init__(self):
'''Constructor'''
self.alphabet = [chr(i) for i in range(32, 127)]
self.alphabet_size = len(self.alphabet)
self.clear_text = ""
self.code = ""
def encode(se... |
from cs50 import get_int
def main():
"""
Print out a pyramid with '#' for the height chosen by the user
"""
# Store int from user in a variable
height = get_valid_int("Height: ")
# Loop over the number of rows
for row in range(1, height + 1):
# Calculate and store the number of ... |
print("Code start")
# task 1: replace name
print("Hello, my name is", "kasturi")
print("and I'm learning Python.")
# task 2: calculate math expression
c=2894//274
print(c)
print(c**4)
#Let's use recently acquired knowledge to solve the next task.
#Task
#In the first print replace "name" with your name.
#Calculate ... |
# Module for reading CSV files
import os
import csv
#locate file to read
csvpath = os.path.join('election_data.csv')
#Variable
TotalVotes = 0
KhanVotes = 0
CorreyVotes = 0
LiVotes = 0
OtooleyVotes = 0
#open the csv
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#... |
import csv
import os
import math
import operator
'''
External Reference used
https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/
https://realpython.com/welcome/
'''
#Loading Training data sets from inputdata.txt file
def loadDataSet():
dataPoints = []
... |
def fac(n):
if n > 1:
return fac(n-1) * n
else:
return 1
print(fac(3))
def fac2(n):
def loop(n, ans):
if n > 1:
return loop(n-1, ans*n)
else:
return ans
return loop(n, 1)
print(fac2(4))
def fac3(n):
ans = 1
while n > 1:
n, ans =... |
import pygame
from player import Player
# Setup pygame
pygame.init()
# Create color constants
WHITE = (255, 255, 255)
BLACK = (255, 255, 255)
# Setup the display window
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Sprite ... |
#!/bin/python3
""" Extra Long Factorials:
You are given an integer N. Print the factorial of this number
Inputs:
- line 1:: a single integer N
Output:
- the factorial of integer N
"""
import math
# nothing special, python does this automagically
n = int(input().strip())
print(math.factorial(n)) |
#!/bin/python3
""" Staircase:
Given a required height N, draw a staircase with '#' symbols that goes
from left to right, and is N steps high
Input:
- line 1:: You are given an integer N - the staircase height
Output:
print a staircase of height N
"""
# Input Line 1 (N)
n = int(input().strip(... |
""" Simple Array Sum:
You are given an array of integers of size N. Can you find the sum of the
elements in the array?
Input:
- Line 1:: an integer N
- line 2:: an N space-separated list of integers representing the array
elements
Output:
A single value equal to the sum of ... |
# Created by Alex Hurtado
import sqlite3
import click
import os
import datetime
class Planner(object):
"""Defines a Planner class"""
def __init__(self, db_name='planner.db'):
self.db_name = db_name
self.connected = None
self.PATH = os.path.dirname(os.path.realpath(__file__))
s... |
# -*- coding: UTF-8 -*-
"""Resume Analysis Module."""
import os
import string
# Counter is used later in the program
from collections import Counter
# Paths
resume_path = os.path.join(".", "Resources", 'resume.md')
# Skills to match
REQUIRED_SKILLS = {"excel", "python", "mysql", "statistics"}
DESIRED_SKILLS = {"r",... |
import collections
def read_trigrams(filename):
file = open(filename, "r")
words = dict()
for line in file:
items = line.split()
words[items[0].strip()] = int(items[1].strip())
vocab = collections.Counter(words)
return vocab
def write_trigrams(trigrams,filename):
with open(filename,"w") as f:
for key... |
x,y=input().split()
x=int(x)
y=int(y)
magazine=input()
note=input()
note_list=list(note.split())
magazine_list=list(magazine.split())
mag={}
#Converting magazine_list to the Dictionary for account of words present in the list.
for i in magazine_list:
if(i in mag):
mag[i]=mag[i]+1
else:
mag[i]=1
... |
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
total_length = len(s)
visited = [[False for x in range(total_length)] for y in range(total_length + 1)]
for length in range(total_length, 0, -1):
for start_index in ra... |
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def get_repeated_set(num_list):
repeated_set = set()
prev = num_list[0]
for curr in num_list[1:]:
if curr == prev:
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# Get index of nodes
... |
#Program for creating new Buttons
import pygame
pygame.init()
BLACK = (0, 0, 0)
GREY=(50,50,50)
WHITE = (255, 255, 255)
BLUE=(127,255,212)
WIDTH = 14
HEIGHT = 14
MARGIN = 1
r=int(input('Enter no. of rows: '))
c=int(input('Enter no. of cols: '))
name=input('Enter B_Name: ')
temp=WIDTH+MARGIN
WINDOW_SIZE = [temp*c, t... |
"""
Python script to perform the hungarian method of solving the assignment problem
While making this, certain python features were avoided in some instances to ensure
people using other languages may read the code
"""
def get_subjects():
""" Gets the list of subjects that should be taught from the user """
number_o... |
import numpy
import pandas
x=pandas.read_csv("car_price.csv",header=0,usecols=[1,3,4,5,6,7,8,9,10,12],converters={i: str for i in range(13)})
#print(x)
####_____________________________________________________DATA_PREPROCESSING
####_________________________MAX_POWER
temp=[]
zeros=0
for each in x['max_power']:
if... |
# implementation of card game - Memory
import simplegui
import random
state = 0
numbers = []
first_pos = 0
second_pos = 0
#exposed = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
#exposed = ["false","false","false","false","false","false","false","false","false","false","false","false","false","false","false","fal... |
numb1 = input("Enter a number : ")
numb2 = input("Enter another a number : ")
result = float(numb1) + float(numb2)
print(result)
|
def uniques_only(arr):
return list(set(arr))
# sets are unordered - arr should be return in same order but dupes removed
def uniques_only(arr):
items = []
for i, item in enumerate(arr):
if item not in arr[:i]:
items.append(item)
return items
# Here we're slicing the sequence tha... |
def containsCloseNums(nums, k):
'''
are there duplicate numbers k indices apart?
'''
if len(nums) <= 1:
return False
ht = {}
for key, value in enumerate(nums):
if value in ht and key - ht[value] <= k:
return True
ht[value] = key
return False
|
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
'''
Approach:
1. Edge case: n == 0, just return the list.
2. Establish nodes for head, last, and previous (one before start).
3. Edge case: I... |
number_of_runs = 0
total_time = 0
while True:
one_run = input("Enter 10 km run time, or 'q' to exit: ")
if one_run == 'q':
break
else:
number_of_runs += 1
total_time += float(one_run)
average_time = total_time / number_of_runs
print(f"Average of {average_time}, over {number_of_r... |
def areFollowingPatterns(strings, patterns):
'''
if the string follows the pattern then true
if the string doesn't follow the pattern false
verify string an pattern are same lenghth = base case
set dict
loop through string for words
loop through pattern for assigned pattern
compare ret... |
# for checking palindrome
s =input("enter the word:")
z=s[::-1]
if s ==z:
print("word is a palindrome")
else:
print{"word is not palindrome"} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import graphSearch
import popularity
import nltk
def getPersonality(text):
names = []
personalitiesFile = open ("../entityExtraction/personalities.txt", 'rb')
personalitiesList = {}
for line in personalitiesFile:
personalitiesList = eval(line)
for p , value in pe... |
import random
class Card:
#Card class has instance attributes: suit, rank and value
#value ranges from 0-9 since the game is baccarat
def __init__(self, suit, rank):
#suit converter
if suit == 1:
self.suit = "Spades"
if suit == 2:
self.suit = "Clubs"
... |
# 적절한 형식으로 공연장 정보를 출력
def print_all_buildings(db):
print("--------------------------------------------------------------------------------")
print_form = '%-10s%-34s%-14s%-14s%-s\n'
column = print_form % ('id', 'name', 'location', 'capacity', 'assigned')
print(column + "---------------------------------... |
'''
cs5001
fall 2018
final project (othello)
'''
import turtle
import collections
import random
# CONSTANTS
SQUARE = 50
PAD = SQUARE/2
TILE_SIZE = 20
BOARD_SIZE = 8
BLACK = "black"
WHITE = "white"
PLAYER = collections.deque([BLACK, WHITE])
SPACES = []
COORDINATES = []
FONT = ("Arial", 14, "normal")
black_legal_moves... |
from typing import List
LengthOfList = 10
########################## Hashing algorithm (Task 2.3(
def hashing(id):
firstpart = ""
for i in range(2):
char = str(ord(id[i]))
firstpart = (firstpart + char)
for i in range(2, 6):
char = id[i]
firstpart = (firstpart + char)
... |
# Normal Solution
def addDigits(num):
i = 0
digits = []
sum = 0
while num > 0:
digits.append(num % 10)
num = num // 10
i = i + 1
for i in digits:
sum += i
if sum / 10 >=1:
return addDigits(sum)
else:
return sum
print(addDigits(38))
# Another ... |
def maxProfit(prices):
mins = prices[0]
maxs = 0
for i in range(len(prices)):
mins = min(mins,prices[i])
maxs = max(maxs,prices[i] - mins)
return maxs
print(maxProfit([7,1,5,3,6,4]))
|
#!/usr/bin/python3
def main():
testfunc( 1 , 2 ,3 , 4 ,5 )
testfunca(1 ,2, 3 ,4 ,one = 1 , two = 2 , seven = 7)
# multiple arguments rep by *args
def testfunc(that , *args):
print(that , args)
for i in args:
print(i, end = "")
# Key word arguments to a fuction
def testfunca(*args ,**kwargs):
print(args ,kw... |
count_w_s=7
count_w_m=6
count_w_l=2
count_b_s=8
count_b_m=5
count_b_l=2
def available(color,size):
global count_w_s
global count_w_m
global count_w_l
global count_b_s
global count_b_m
global count_b_l
if color=="white":
if size=="s" and count_w_s != 0:
count_w_s-=1
... |
#Hailstone Sequence
number=input("Give me a number greater than zero!")
if number<=0:
number=input("READ THE INSTRUCTIONS: Give me a number greater than zero!")
while (number!=1):
if number%2==0:
number=number/2
else:
number=(number*3)+1
print number
if number ==0:
... |
"""A memory/matching game.
Use A and B to move around the screen. Press A+B together to see a card. Try and find
matches.
The code purposely only uses lists and dictionaries as its most advanced data structures.
It's also incomplete in a number of ways - feel free to make changes and see if you can
improve it!
"""
i... |
#https://www.w3schools.com/python/python_howto_remove_duplicates.asp
def remove_duplicat(x):
#Create a dictionary, using the List items as keys. This will automatically remove any duplicates because dictionaries cannot have duplicate keys.
return list(dict.fromkeys(x))
my_list=["a","b","c","c"]
print(rem... |
class Vertex:
def __init__(self, n):
self.name = n
self.neighbors = list()
def add_neighbor(self, v):
if v not in self.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
self.visited = False
class Graph:
vertices = {}
def add_vertex(... |
class battedball:
"""
modularizes the battedball method collection into a class object.
bbclass can only be defined if the valid json, csv, and txt files
are located in the Data subdirectory of the working folder
"""
# initialization routine
def __init__(self):
self.player_... |
def gcd(m,n):
while m%n != o:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
class Fraction:
def __init__(self,top,bottom):# this is known as constructor
self.num = top
self.den = bottom
def __str__(self):# function that print the exact value without printing the address like 0x40bc...
retur... |
class Solution(object):
def __init__(self):
self.direction=[]
self.direction.append([0,1])
self.direction.append([0,-1])
self.direction.append([1,0])
self.direction.append([-1,0])
self.row = 0
self.col = 0
def solve(self, board):
"""
:t... |
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
diff = 0xffffffff
nums = sorted(nums)
for i in range(len(nums)):
low = i + 1
high = len(nums) - 1
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@staticmethod
def inOrderRec(root):
"""
递归中根遍历
:param root: TreeNode
:return:
"""
if not root:
... |
'''
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
'''
# Tags: Tree Traversal (Level Order)
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution... |
'''
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], ... |
# Your code here
def finder(files, queries):
"""
YOUR CODE HERE
"""
files_found = []
directory = {}
for file in files:
# keyName is last part of path
parts = file.split("/")
keyName = parts[-1]
# create a new entry in the dictionary if needed
... |
"""
Задача D. Сумма факториалов
По данному натуральном n вычислите сумму факториалов.
В решении этой задачи можно использовать только один цикл.
Вводится натуральное число n.
"""
n = int(input())
previous_factorial = 1
sum_factorials = 0
for i in range(1, n+1):
current_factorial = previous_factorial * i
sum... |
"""
Задача B. Обнулить последние биты
Напишите программу, которая обнуляет заданное количество последних бит числа
"""
number, i = [int(i) for i in input().split()]
# обнуляю i последние бит
result = number >> i << i
print(result) |
from data_structure.stack import Stack
def test_push():
stack = Stack()
stack.push(1)
assert stack.back() == 1
assert stack.size == 1
stack.push(3)
assert stack.back() == 3
def test_pop():
stack = Stack()
stack.push(1)
assert stack.size == 1
assert stack.pop() == 1
ass... |
"""
Задача A. Установить значение бита в 1
Напишите программу, которая в заданном числе устанавливает
определенный бит в 1 (биты при этом нумеруются с нуля, начиная от младших).
"""
a, i = [int(i) for i in input().split()]
result = (1 << i) | a
|
"""
Задача A
Даны два списка A и B упорядоченных по неубыванию.
Объедините их в один упорядоченный список С
(то есть он должен содержать len(A)+len(B) элементов).
Решение оформите в виде функции merge(A, B), возвращающей новый список.
Алгоритм должен иметь сложность O(len(A)+len(B)).
Модифицировать исходные списки зап... |
"""
Задача G. Ручная сортировка
Вам необходимо реализовать алгоритм сортировки merge-sort.
"""
from algoritms.sorting.merge_sort import merge_sort
if __name__ == '__main__':
_ = input()
arr = [int(i) for i in input().strip().split()]
sorted_arr = merge_sort(arr)
for val in sorted_arr:
print(... |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
###################################################
# INSTRUCTOR INPUT BLOCK
# THIS CELL WILL BE REPLACED BY GRADER INPUT... |
'''
Um funcionário recebe um salário fixo mais 4% de comissão sobre as vendas. Faça um programa
que receba o salário fixo do funcionário e o valor de suas vendas, calcule e mostre a comissão e seu
salário final.
'''
salario_fixo = float(input('Digite o salário fixo: '))
valor_vendas = float(input('Digite o valor de v... |
#pegar a distância
distancia = float(input())
if(distancia >0 and distancia <= 200):
op1 = distancia * 0.50
print(op1)
elif(distancia > 200):
op2 = distancia * 0.45
print(op2)
else:
print('Possivelmente o valor é negativo.')
|
''' Q7
Elabore um programa que preencha uma matriz M de ordem
6x4 e uma segunda matriz N de ordem 6x4, calcule
e imprima a soma das linhas de M com as colunas de N.
'''
'''
m = []
n = []
#criando a matriz m
for i in range(3):
linha = []
for j in range(2):
linha.append(int(input()))
m.append(linha)
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.