text stringlengths 37 1.41M |
|---|
# -*- coding:utf-8 -*-
"""
我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。
请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。
示例 1:
输出:low = 100, high = 300
输出:[123,234]
示例 2:
输出:low = 1000, high = 13000
输出:[1234,2345,3456,4567,5678,6789,12345]
提示:
10 <= low <= high <= 10^9
"""
class Solution(object):
def sequentialDig... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
"""
def lengthOfLastWord(s):
s = s.strip()
s_list = s.split(' ')
return len(s_list[-1])
print(lengthOfLastWord('a ')) |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。
如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false。
示例 1:
输入:arr = [1,2,2,1,1,3]
输出:true
解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。
示例 2:
输入:arr = [1,2]
输出:false
示例 3:
输入:arr = [-3,0,1,-3,1,1,1,-3,10,0]
输出:true
提示:
1 <= arr.length <= 1... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
示例 1:
输入:
5
/ \
4 5
/ \ \
1 1 5
输出:
2
示例 2:
输入:
1
/ \
4 5
/ \ ... |
# -*- coding:utf-8 -*-
"""
给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。
题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。
示例 1:
输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
输出:"Sao Paulo"
解释:从 "London" 出发,最后抵达终点站 "Sao ... |
# -*- coding:utf-8 -*-
"""
二指输入法定制键盘在 XY 平面上的布局如上图所示,其中每个大写英文字母都位于某个坐标处,例如字母 A 位于坐标 (0,0),字母 B 位于坐标 (0,1),字母 P 位于坐标 (2,3) 且字母 Z 位于坐标 (4,1)。
给你一个待输入字符串 word,请你计算并返回在仅使用两根手指的情况下,键入该字符串需要的最小移动总距离。坐标 (x1,y1) 和 (x2,y2) 之间的距离是 |x1 - x2| + |y1 - y2|。
注意,两根手指的起始位置是零代价的,不计入移动总距离。你的两根手指的起始位置也不必从首字母或者前两个字母开始。
示例 1:
输入:wo... |
# -*- coding:utf-8 -*-
"""
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:
输入:
["MaxQueue","pop_front","max_... |
# -*- coding:utf-8 -*-
"""
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 02 = 1
"""
class SetSolution(object):
def isHappy(self, n):
"""
... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
"""
from utils.TreeNode import TreeNode
class Solution(object):
def minDepth(self, root):
"""... |
# -*- coding:utf-8 -*-
"""
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
著作权归领扣网络所有。商业转载... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
对链表进行插入排序。
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。
插入排序算法:
插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入... |
"""
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的
进阶:使用 O(1) 额外空间复杂度的原地解法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-words-i... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
bfs:
每一次都加上所有硬币,因为是广度遍历,所得到第一次得到的结果一定是可以用最少硬币达到的
""... |
# -*- coding:utf-8 -*-
"""
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
注意:本题与主站 105 题重复:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-ino... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
示例:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
说明:
数组仅可以在 update 函数下进行修改。
你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。
"""
... |
# -*- coding:utf-8 -*-
"""
给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
示例 3:
输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]
示例 4:
输入:root1 = [0,-10,10], ro... |
# -*- coding:utf-8 -*-
"""
房间中有 n 枚灯泡,编号从 1 到 n,自左向右排成一排。最初,所有的灯都是关着的。
在 k 时刻( k 的取值范围是 0 到 n - 1),我们打开 light[k] 这个灯。
灯的颜色要想 变成蓝色 就必须同时满足下面两个条件:
灯处于打开状态。
排在它之前(左侧)的所有灯也都处于打开状态。
请返回能够让 所有开着的 灯都 变成蓝色 的时刻 数目 。
示例 1:
输入:light = [2,1,3,5,4]
输出:3
解释:所有开着的灯都变蓝的时刻分别是 1,2 和 4 。
示例 2:
输入:light = [3,2,4,1,5]
输出:2
解释:所有开着的灯都变蓝... |
# -*- coding:utf-8 -*-
"""
给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 6
示例 2:
输入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
输出: 42
"""
# Definition for a binary tree node.
class TreeNode:
def __in... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定由若干 0 和 1 组成的矩阵 matrix,从中选出任意数量的列并翻转其上的 每个 单元格。翻转后,单元格的值从 0 变成 1,或者从 1 变为 0 。
返回经过一些翻转后,**行上所有值都相等的最大行数**。
示例 1:
输入:[[0,1],[1,1]]
输出:1
解释:不进行翻转,有 1 行所有值都相等。
示例 2:
输入:[[0,1],[1,0]]
输出:2
解释:翻转第一列的值之后,这两行都由相等的值组成。
示例 3:
输入:[[0,0,0],[0,0,1],[1,1,0]]
输出:2
解释:翻转前两... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
写一个程序,输出从 1 到 n 数字的字符串表示。
1. 如果 n 是3的倍数,输出“Fizz”;
2. 如果 n 是5的倍数,输出“Buzz”;
3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。
示例:
n = 15,
返回:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
注意数组中可能存在重复的元素。
示例 1:
输入: [1,3,5]
输出: 1
示例 2:
输入: [2,2,2,0,1]
输出: 0
说明:
这道题是 寻找旋转排序数组中的最小值 的延伸题目。
允许重复会影响算法的时间复杂度吗?会如何影响,为什么?
相关题
33_搜索旋转排序数组
81_搜索旋转排序数组 II
153_寻找旋转排序数组中的最... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
"""
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27
输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
示例 4:
输入: 45
输出: false
"""
def isPowerOfThree(n):
"""
:type n: int
:rtype: bool
"""
while n > 1:
if n % 3 != 0:
break
n ... |
# -*- coding:utf-8 -*-
__author__ = 'huanghf'
# Definition for a binary tree node.
from utils.TreeNode import TreeNode,List2TN
class Solution(object):
def preorderTraversal(self,root):
"""
根->左->右
:type root: TreeNode
:rtype: List[int]
"""
stack = [root]
r... |
#Question1
class Flower():
def flower_attribute(self):
print('The most Beautiful Flower')
class Lotus(Flower):
print('Lotus is the national flower of india')
lot=Lotus()
lot.flower_attribute()
#Question2
#Output is given as following:
#print a.f() = A
#print b.()= B
#Question3
class Cop():
def __i... |
_list = [1,1,3]
sum = 3
class Test:
def match(self,_list,sum):
for i in range(len(_list)):
for j in range(i+1,len(_list)):
if _list[i] + _list[j] == sum:
print('match found')
return
print('no match found')
@staticmethod
def static_match(_list,sum):
for i in range(len(_list)):
for j in r... |
# # This is to read line in text file
with open("C:\Users\Admin\Documents\\readline.txt", 'r') as f:
lines = f.readlines()
fp = open("C:\Users\Admin\Documents\\writer.txt", 'w+')
# fp.write()
print(fp.read())
print(lines[1])
print(lines)
print (len(lines))
for l in lines:
... |
# class in object oriented programming
class computer:
def config(self, cpu, ram, brand):
print (self.cpu, self.ram, self.brand)
print ("i5", "32gb", "10gb Ram")
comp1 = computer()
comp2 = computer()
# computer.config(comp1)
comp1.config()
comp2.config("i3", "32", "hp") |
from machine import *
def print_field():
print(" 0 1 2")
for i in range(3):
print("{0} {1} {2} {3}".format(i, field[i][0], field[i][1], field[i][2]))
def is_win(who):
for i in range(3):
if check_row(who, i) == 3:
return True
for i in range(3):
if check_col(who, i)... |
#week2 -- day11
# logical operators in python:
# using and & or operators in this example:
x=5
print(x>3 or x<4 ) # return true becouse one of condition are true.
print(x<10 and x>4) # return true becouse both of condition are true.
################################
# python identity operators
# يستخدم العامل isللمقا... |
#week4 __ day23
# To determine if a specified key is present in a dictionary use the in keyword:
my_dict ={
"name":"muteb",
"f_name":"alotaib",
"age":34
}
print(my_dict)
if "f_name" in my_dict:
print("yes 'f_name' is one of key on the my_dict dictionary")
#+++++++++++++++++++++++++++++
#To determine how ... |
# week3 __ day15
#To determine how many items of index has, use the len() method.
list_of = ["apple","banana","orange","cherry"]
print(len(list_of))
#+++++++++++++++++++++++++++++
# to add a new elemnent in end of index we use the append() method.
mylist=["apple","banana","orange","cherry"]
mylist.append("stroberry"... |
def sort_letters(word):
letter_list = list(word)
letter_list.sort()
return ''.join(letter_list)
def passphrase_is_valid(passphrase: str) -> bool:
words = [sort_letters(word) for word in passphrase.split()]
word_set = set(words)
return len(words) == len(word_set)
def count_valid_in_input():
... |
#This file will make the graph on matplotlib
#importing all libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
class create_matPlotLib_Graph():
def __init__(self):
self.game_data = pd.read_csv('data/Video_Games_Sales.csv')
self.shootings_data = pd.read_csv('data/sc... |
def main():
print("Caesar cipher")
print()
key = eval(input("Enter the key value: "))
plain = input("Enter the phrase to encode: ")
cipher = ""
for word in plain.split():
for letter in word:
cipher = cipher + chr(ord(letter) + key)
cipher = cipher + ' ' ## put... |
# Problems: #01,#02,#03,#04,#05,#06,#07,#YouTube
#01
################################################
## Zelle 7.1. – compute wages with OT ##
################################################
# Definition to calculate wage and OT
def wages(OT,wage,hours):
earned = 0
# If the hours hit to Overtime pay... |
# Write a function aGreetsb (a,b), which has a introduce
# themselves to b and b introduce themselves to a.
# The definition here is taking in a variable and using that variable as person.
# When the variable comes in, in () it is used as the definitions () in
# this case, person. It then uses that variable in the def... |
# Assume the days of the week are numbered 0,1,2,3,4,5,6 from Sunday to Saturday.
# Writea function, dayNum2day(dayNum), which is given the day number, and
# which returns the day name (a string). Use a for loop to cycle over all the
# numbers and print out the corresponding day name. Use if elif.
daysOfTheWeek = [... |
from random import randint
rollOfDice = {}
def randRoll(dice):
counter = 0
for i in range(dice):
randNum = randint(1,6)
counter += randNum
return counter
def runThrough(n,dice):
for i in range(n):
poop = randRoll(dice)
if poop in rollOfDice:
rollOfDice[poop... |
# The main function of the program
def main():
print ('Find your average score!')
print ()
# Asking user for 3 inputs and consecutively assigning them to
# the 3 variables to the left
s1, s2, s3 = eval(input("Enter 3 scores separated by commas: "))
# The math to find an average of 3 numbers
... |
def nthLtr_nTimes(word):
L = []
counter = 1
for letter in word:
L.append(letter*counter)
counter += 1
return L
def putSpaceBtwnLtrds(Strg):
Split = []
Joined = ''
for letter in Strg:
Split.append(letter)
counter = 0
for i in range (len(Split) - 1):
J... |
import turtle
from math import *
from random import randint
wn = turtle.Screen()
wn.bgcolor('Dark Slate Gray')
wn.title('Kokoro saves your heart')
kokoro = turtle.Turtle()
colorList = ['Purple','Deep Pink','Red','Dark Orange','Yellow','Lime Green','Deep Sky Blue','Midnight Blue']
kokoro.color('Medium Turquoise','Pur... |
def toCm(inches):
cm = inches * 2.54
return cm
def wholeFeetFrom(inches):
wholeFeet = inches // 12
return wholeFeet
def leftOver(inches):
leftOver = inches % 12
return leftOver
def wholeMetersFrom(cm):
cm = toCm(cm)
meters = cm // 100
return meters
def remaining(cm):
cm = toC... |
'''Find all perfect numbers <=10,000.
A positive int > 1 is perfect if it equals
the sum of its factors starting with 1 but not
including the number itself.
For EX. 8 is not since 1+2+4 != 8.'''
#YouTube
################################################
## YouTube ##
#####... |
def main():
# Setting up a variable with the alphabet so that I can use it
# to count 1 - 26 for the program (faster and less code)
alpha = 'abcdefghijklmnopqrstuvwxyz'
# Setting up a variable to start at 0
added = 0
# take in users word
fullName = input('Please enter your full name. ')
... |
def encodeCharCir(c,n):
alfa = 'abcdefghijklmnopqrstuvwxyz'
ndx = alfa.find(c)
new_ndx = (ndx + n) % 26
new_char = alfa[new_ndx]
return new_char
def main():
for c in 'abcdefghijklmnopqrstuvwxyz':
print(c,encodeCharCir(c,3))
if __name__ == '__main__':
main()
|
'''The speeding ticket fine policy in Podunksville is $50 plus $5 for
each mph over the limit plus a penalty of $200 for any speed over 90
mph. Write a program that accepts a speed limit and a clocked speed
and either prints a message indicating the speed was legal or prints
the amount of the fine, if the speed is ille... |
# Problems: #01,#02,#03,#04,#05,#06,#YouTube https://youtu.be/OJMoQumklwg
#01
################################################
## Zelle 8.1 ##
################################################
def fib(n):
# Setting up the first two numbers of the Fibinacci sequence
L = [1,1]
... |
L = [1,2,3,4,5,6,7,8]
def productAcum(L):
''' Returns the product of the numbers in list L. There is a bug in
this program. Can you find it & fix it?
'''
p = 1
for n in L:
p = p*n
return p
print (productAcum(L))
|
def appending(doc):
doc = doc.split('\n')
for row in doc:
print (row)
def max_min_Avg(fname):
inFile = open(fname, 'r')
docData = inFile.read()
inFile.close()
appending(docData)
for row in docData:
print(row)
max_min_Avg('quiz5Floats.txt')
|
# 1
# # # # # # # # # #
# c03ex01.py
# Volume and serface area of a sphere
import math
def main():
print("This program computes the volume and surface area of a sphere")
print()
r = eval(input("Please enter the radius of the sphere: "))
volume = 4.0/3.0 * math.pi * r**3
area = 4 * math.pi * r**2... |
# Program to check if a given number is automorphic or not
def automorphic_check(number):
squared = str(int(number)**2)
r_squared = squared[::-1]
r_check = []
i = len(number)
for x in r_squared:
if i == 0:
break
r_check.append(x)
i -= 1
check_number = ''.join... |
print("subject total ,if function")
print('......................................................................')
A= int(input ("enter Maths marks:"))
B= int(input ("enter Tamil marks:"))
C= int(input ("enter Arabic marks:"))
Total=(A+B+C)
Average=(A+B+C)/3
print "Total=",Total
print "Average=",Average
if (T... |
a, b = input().split()
a = int(a)
b = int(b)
if a != b:
print(1)
else:
print(0)
'''
a, b = input().split()
x = int(a)
y = int(b)
b1 = bool(x)
b2 = bool(y)
z = int((b1==True and b2==False) or (b1==False and b2==True))
print(z)
'''
|
y, m, d = input().split('.')
print('%04d' % int(y), end='.')
print('%02d' % int(m), end='.')
print('%02d' % int(d))
'''
zfill 함수를 이용한다면
y, m, d = input().split('.')
print(y.zfill(4), m.zfill(2), d.zfill(2), sep = '.')
'''
|
class User:
def __init__(self, first_name, last_name, email_address):
self.first_name = first_name
self.last_name = last_name
self.email = email_address
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
def make_withdrawal(self, ... |
class BankAccount:
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdrawal(self, amount):
self.balance -= amount
if... |
def my_final_grade_calculation(filename):
fp = open(filename, "r")
data = fp.readlines()
my_dictionary = {}
for x in range(0, len(data)):
stripped = data[x].strip().split(',')
for x in range(1, len(stripped)):
stripped[x] = int(stripped[x].strip())
# extract various ... |
import turtle
import random
def dragonIteration(string):
rslt = ""
i = 0
while i < len(string):
if string[i] == 'X':
rslt += "X+YF"
elif string[i] == 'Y':
rslt += "FX-Y"
else:
rslt += string[i]
i += 1
return rslt
def draw(myTrt, string, angle):
myTrt.hideturtle()
myTrt.pu()
myTrt.setposit... |
# This exercise contains a simple program that will generate a random number
# in the range of 1 to 10.
import random
print(random.randint(1,10))
|
#!/usr/bin/env python
import socket
import sys
from datetime import datetime
# Ask for input
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
portStart = int(raw_input("Start of port range: "))
portEnd = int(raw_input("End of port range: "))
... |
# https://www.geeksforgeeks.org/google-interview-experience-off-campus/
votes = {}
mappingOfIdxToId = {}
mappingOfIdToIdx = {}
# at zero position we will be storing the idx in the heap
# and at second position we will be storing the count of votes
idx = 0
def voteCandidate(id):
if id in votes:
votes[id] = ... |
# https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversa/
# o(n) Implementation
# It contains the O(n) implementation of creating a binary search tree from preorder traversal
class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def prin... |
# class LinkedList:
# next,
# prev
# Merge Sort Implementation
def msort(list):
if len(list)<=1:
return
mid = len(list)//2
L = list[mid:]
R = list[:mid]
msort(L)
msort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
list[k] = L[i]
... |
# https://www.geeksforgeeks.org/connect-nodes-at-same-level/
def constructUtil(pre, low, high):
# print (low, high)
if low > high or high >= len(pre):
return None
root = Node(pre[low])
if low == high:
return root
# remember to handle the edge case if there is no node
par = high+... |
thisdict = {
1 : 3,
3 : 5,
5 : 7
}
name_of_count_el = 5
spisok = []
for x, y in thisdict.items():
spisok.append(x)
spisok.append(y)
print(spisok.count(name_of_count_el)) |
#nを素因数分解したリストを返す
def prime_factor(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
|
def search(q,w,e,r):
if e==r:
assert w==q[r]
return r
else:
middle=(e+r)//2
if w>q[middle]:
return search(q,w,middle+1,r)
else:
return search(q,w,e,r)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 15:53:47 2020
@author: ioana
"""
import numpy as np
import random
import matplotlib as mpl
#the activation function:
def sigmoid(x):
return 1.0/(1+ np.exp(-x))
#the derivate of te activation function
def sigmoid_derivative(x):
return x * (1.0 - x)
class Neura... |
import json
import urllib2
_author__ = "Edwin Hernandez, PhD"
__copyright__ = "Copyright 2018, Edwin Hernandez LLC"
__version__ = "0.1"
class BTCPricing(object):
currencies= ["usd", "eur"]
coins = ["btc", "ltc", "eth"]
url="https://www.bitstamp.net/api/v2/ticker/"
def BTCPricing(self)... |
"""
Ukkonens implementation
Author: Kevin Lew
Student ID: 29677475
"""
class Node():
"""Class representing a node
"""
def __init__(self):
"""constructor for node
"""
self.edges = []
self.suffixind = -1 # used for calculating suffix array
def get_len(self)... |
"""
Program: test_half_birthday.py
Author: Shiqi Wang
Last date modified: 10/13/2020
The purpose of this program is to test function half_birthday
"""
import unittest
from main.half_birthday import half_birthday
from datetime import datetime
class TestHalfBirthday(unittest.TestCase):
def setUp(sel... |
"""
Program: test_valid_input_in_functions.py
Author: Shiqi Wang
Last date modified: 09/10/2020
The purpose of this program is to test function score_input
"""
import unittest
from more_functions.validate_input_in_functions import score_input
class ScoreInputCase(unittest.TestCase):
def test_scor... |
"""
Program: unit_test.py
Author: Shiqi Wang
Last date modified: 09/02/2020
The purpose of this program is to be convert input years to months
"""
def convert_to_months(years):
try:
age_in_years = int(years)
except ValueError:
raise TypeError("Input number is not integer")
... |
"""
Program: database_test.py
Author: Shiqi Wang
Last date modified: 12/12/2020
The purpose of this program is to test methods from class Database
"""
import unittest
from main.Database import Database
class MyTestCase(unittest.TestCase):
def setUp(self):
self.database = Database("test_log.d... |
#!/usr/bin/python3
"""
a Python script that takes in a string and sends a search request
to the Star Wars API
"""
import requests
from sys import argv
if __name__ == "__main__":
req = requests.get('https://swapi.co/api/people',
params={'search': argv[1]})
counter = req.json().get('count... |
#!/usr/bin/python3
"""
A function that prints "My name is __ __"
"""
def say_my_name(first_name, last_name=""):
""" Prints first name and last name else TypeError """
if not isinstance(first_name, str):
raise TypeError("first_name must be a string")
if not isinstance(last_name, str):
raise... |
#!/usr/bin/python3
""" Checks if the object is an instance of a class """
def is_kind_of_class(obj, a_class):
""" Returns True or False upon checking """
return isinstance(obj, a_class)
|
#! usr/bin/env python
'''
http://projecteuler.net/problem=10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
This problem is similar to p7. only need to add the primes.
Answer: 142913828922
'''
index = 2000000
primes = [2]
num = 3
while num <= index:
dont_add ... |
numbers = [1,2,3,4,5,6,7,8,9,11,13]
i = 0
oddnumbers = 0
evennumbers = 0
while i < len(numbers):
if numbers[i] % 2 == 1:
oddnumbers += 1
i = i + 1
elif numbers[i] % 2 == 0:
evennumbers += 1
i = i + 1
print(oddnumbers)
print(evennumbers)
|
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
def strange ():
for i in range(30):
teal_line = canvas.create_line(0, 300-i*20, 300-i*20, 300, fill='green')
teal_line = canvas.create_line(20*i, 0, 300, i*20, fill='purple')
strange()
root.mainloop... |
filename = 'alma.txt'
# create a function that reads a file and prints it's
# lines, also it should prepend an 'A' character
# to each line
fname = "cv-anakin.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
print(line.rstrip() + "A\n"... |
a = "*"
maxstar = 6;
i = 0;
j = 0;
for j in range(2):
if j == 1:
while i>0:
print (a*(i-1))
i -= 1;
if i == 0:
exit()
for i in range(maxstar):
print (a*i)
if i == 5:
j += 1;
|
import random
import character
from view import View
### Battle ###
class Battle:
def __init__(self,hero,boss):
self.hero = hero
self.boss = boss
def fight(self):
### HERO AND BOSS POSOTION ###
if self.hero.x_pos == self.boss.x_pos and self.hero.y_pos == self.boss.y_pos:
... |
#TEST THE FUNCTIONS
import unittest
import your_name_work
class PrimesTestCase(unittest.TestCase):
"""Tests for `isAnagram.py`."""
def test_anagram(self):
self.assertTrue(your_name_work.anagramm("Alma","ma la"))
self.assertTrue(your_name_work.anagramm("Alma","ma la"))
# """Tests for ... |
# create a 300x300 canvas.
# draw a green 10x10 square to its center.
from tkinter import *
root = Tk()
x = 300
y = 300
canvas = Canvas(root, width= x, height= y )
canvas.pack()
def square(x,y,size):
teal_line = canvas.create_line(x/2 - size/2 , y/2 - size/2, x/2 + size/2 , y/2 - size/2, fill='green')
tea... |
from tkinter import *
import time
import random
root = Tk()
canvas = Canvas(root, bg="black", width='600', height='600')
canvas.pack()
a=10
def magic(x,y,number,size,number_begin):
# if number_begin == number:
# topleft = ( 0, a+0)
# topright = (size,a+0)
# bottom = ( size*(3**0.5)/3.46... |
# Create a function that prints a diamond like this:
# *
# ***
# *****
# *******
# *********
# ***********
# *********
# *******
# *****
# ***
# *
#
# It should take a number as parameter that describes how many lines the diamond has
def star_number(number):
for i in... |
n=int(input())
def fibonacci(n):
f=[0,1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
return f[n]
print(fibonacci(n))
|
class Solution:
str = input("enter the IP address :")
str = str.split('.')
#ip CLASS A,B,C,D,E
if int(str[0]) >=1 and int(str[0]) <=127 : print("Output: Class A", end = ' ')
elif int(str[0]) >= 128 and int(str[0]) <= 191: print("Output: Class B", end = ' ')
elif int(str[0]) >= 192 and int(str[0]... |
a=1000
b=5000
if a<b:
print("number is greater",a)
if a>b:
print("number is greater",b) |
#funcao principal Encaixa ou Nao
def solucao(a, b):
#procurar na string a, a partir do índice (len(a) - len(b))
#ate o fim de a, pela string b
#string.fin(substring) retorna -1 caso nao encontre a substring em
#questao. caso contrario, retorna o index de onde a substring comeca
#retorna '... |
def solucao(str):
metade = len(str)//2 - 1
line = ""
for i in range(metade, -1, -1):
line += str[i]
for i in range(len(str)-1, metade, -1):
line += str[i]
print(line)
return line
n = int(input())
for i in range(n):
line = str(input())
solucao... |
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to manage bullets fired from the elephant"""
def __init__(self, ai_game):
"""Create a bullet object at the elephants's current position."""
super().__init__()
self.screen = ai_game.screen
... |
def missing_element(a1,a2):
for element in a1:
if element not in a2:
return element
return 0
|
# Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Решите задание в одну строку.
# Подсказка: используйте функцию range() и генератор.
twenty = {el for el in range(20, 240, 20)}
print(twenty)
twenty_one = {el for el in range(21, 240, 21)}
print(twenty_one)
|
# Реализовать функцию my_func(), которая принимает три позиционных аргумента и возвращает сумму наибольших двух аргументов.
s1 = int(input('Введи первое число: '))
s2 = int(input('Введи второе число: '))
s3 = int(input('Введи третье число: '))
def max_sum(sl1, sl2, sl3):
l = [sl1, sl2, sl3]
l.remove(min... |
# Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
# При вызове функции должен создаваться объект-генератор. Функция вызывается следующим образом: for el in fact(n).
# Она отвечает за получение факториала числа. В цикле нужно выводить только первые n чисел, начиная с 1! и д... |
varA = 5
varB = 10
if ( varA == 5 ):
print ("varA staat gelijk aan 5")
print("extra tab")
else :
print("varA staat niet gelijk aan 5")
varA = 11
if ( varA == varB ) :
print("varA staat gelijk aan varB")
elif ( varA < varB ) :
print("varA is kleiner dan varB")
else :
print("dan is varA groter dan Var... |
'''
This is the base class for room. Rooms types or specific room definitions should extend this class.
'''
#----- Base Python imports------#
import sys
class Room(object):
def __init__(self, name, description, exits):
"""
NB. A list must be passed into exits
"""
self.self = self
... |
import matplotlib.pyplot as plt
import numpy as np
from data import getData, showData
X, y, K = getData()
N, D = X.shape
# hyperparameters
step_size = 1e-0
reg = 1e-3
delta = 1
# initialize parameters randomly
W = 0.01 * np.random.randn(D, K)
b = np.zeros((1, K))
for i in range(200):
scores = np.dot(X, W) + b
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.