text stringlengths 37 1.41M |
|---|
"""
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt()
示例 1:
输入:16
输出:True
示例 2:
输入:14
输出:False
"""
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
if num < 2:
return True
tem... |
"""
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
进阶:
如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
示例 1:
输入:s = "abc", t = "ahbgdc"
输出:true
示例 2:
输入:s = "axc", t = "ahbgdc"
输出:false
"""
class Solution(object):
... |
"""
给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
"""
class Solution(object):
def transpose(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
rows = len... |
"""
在一个给定的数组nums中,总是存在一个最大元素 。
查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
如果是,则返回最大元素的索引,否则返回-1。
示例 1:
输入: nums = [3, 6, 1, 0]
输出: 1
解释: 6是最大的整数, 对于数组中的其他整数,
6大于数组中其他元素的两倍。6的索引是1, 所以我们返回1.
"""
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... |
"""
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if not n: return 0
if n == 1: return 1
if n == 2: return 2
temp_a, temp_b = 1,... |
"""
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
示例 2:
输入:root = [1,2,3], targetSum = 5
输出:false
示例 3:
输入:root = [1,2], targetSum = 0
输出:false
"""
# Definition for a bin... |
"""
自除数 是指可以被它包含的每一位数除尽的数。
例如,128 是一个自除数,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。
还有,自除数不允许包含 0 。
给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。
示例 1:
输入:
上边界left = 1, 下边界right = 22
输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
"""
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
... |
"""
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。
顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
示例 1:
输入:[5,5,5,10,20]
输出:true
解释:
前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
第 5 位顾客那里,我们找还一张 10 美元的钞... |
"""
对于一个 正整数,如果它和除了它自身以外的所有 正因子 之和相等,我们称它为 「完美数」。
给定一个 整数 n, 如果是完美数,返回 true,否则返回 false
示例 1:
输入:28
输出:True
解释:28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, 和 14 是 28 的所有正因子。
"""
class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num < ... |
"""
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
length_nums = l... |
"""
给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从 1 到 n 的 min(ai, bi) 总和最大。
返回该 最大总和 。
示例 1:
输入:nums = [1,4,3,2]
输出:4
解释:所有可能的分法(忽略元素顺序)为:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + mi... |
"""
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于⌊n/2⌋的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
"""
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum_nums = 0
majority = ... |
"""
给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100
输出: "202"
示例 2:
输入: -7
输出: "-10"
"""
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
if abs(num) < 7:
return str(num)
flag = 0
if num < 0:
flag = ... |
"""
在一个由小写字母构成的字符串 s 中,包含由一些连续的相同字符所构成的分组。
例如,在字符串 s = "abbxxxxzyy" 中,就含有 "a", "bb", "xxxx", "z" 和 "yy" 这样的一些分组。
分组可以用区间 [start, end] 表示,其中 start 和 end 分别表示该分组的起始和终止位置的下标。上例中的 "xxxx" 分组用区间表示为 [3,6] 。
我们称所有包含大于或等于三个连续字符的分组为 较大分组 。
找到每一个 较大分组 的区间,按起始位置下标递增顺序排序后,返回结果。
示例 1:
输入:s = "abbxxxxzzy"
输出:[[3,6]]
解释:"xxxx" ... |
"""
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。
s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:
给定的树 s:
3
/ \
4 5
/ \
1 2
给定的树 t:
4
/ \
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, r... |
"""
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
示例 2:
输入: [2,3,0,1,4]
输出: 2
提示:
1 <= nums.length <= 1000
0 <= nums[i] <= 105
"""
class Solution(objec... |
"""
给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
"""
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
max_count = 0
for num in nums:
... |
# coding=utf-8
import numpy as np
'''
一些工具函数
'''
'''
把多维形状展平成一维
'''
def flat_shape(*shape):
#print("shape:", shape)
if len(shape) == 0:
return 1
if len(shape) == 1:
shape = shape[0]
if type(shape) != type(()):
return shape
res = 1
for item in shape:
if type(... |
#user input
num1 = int(input('enter number 1 ')) #takes the input string from user and converts it into a interger type
num2 = int(input('enter number 2 '))
sum_num =num1+num2
print('the sum of the 2 numbers is ', sum_num)
|
# 최대 재귀 깊이(maximum recursion depth)가 1,000
def hello():
print('Hello, world!')
hello()
# hello()
# 테스트 시 997번 찍었네?
def hello(count):
if count == 0: # 종료 조건을 만듦. count가 0이면 다시 hello 함수를 호출하지 않고 끝냄
return
print('Hello, world!', count)
count -= 1
hello(count) # with no return vall... |
Speed = int(input("Enter the Speed: "))
Time = int(input("Enter the Time: "))
Distance_Covered = Speed * Time
print("Total Distance Covered: ",Distance_Covered)
|
for i in range(1,6):
for j in range(1,i+1):
print(j, end="")
print()
print("*" *25)
####################################
for m in range(1,6):
for n in range(1,7-m):
print(n, end="")
print()
print("*" *25)
####################################
for x in range(5):
print(end=" "*x)
for y in range(1,6-x... |
n=int(input("enter the number to which want to see prime"))
count=0
if n>1:
for i in range(2,n+1):
isprime=True
for j in range(2,i//2+1):
if i%j==0:
isprime=False
break
if isprime==True:
print(i,"is a prime number")
count=co... |
# define a function
def front_times(string, front, n):
# create an empty string
str = ""
# get value of n and iterate it, number of times the string should repeat
for k in range(n):
# get value of front and iterate till the character in a string
for i in range(front):
# app... |
age = int(input("Enter your age : "))
maxexp = int(input("Enter your maximum experience : "))
if age > 20 and age < 50:
if maxexp >= 3:
print("Access Granted")
else:
print("You have less experience")
else:
print("You are age is outside the assigned value")
|
# defining function
def printAsterisks(n):
# return how many astrisks want to be printed
return "*"*n
# main program starts here
# get input from user
n = int(input("Enter the numbers of asterisks: "))
# call the function with in print function
print(n,"Asterisks printed", printAsterisks(n))
|
for value in range(1,6):
print("Square value for ",value,"is :",value*value)
|
#import deque function
from collections import deque
#for pop left usage deque([]) below
queue = deque([])
while True:
print("1.Insert element in queue\n2.Remove element from queue\n3.Display element in queue\n4.exit")
choice = int(input("Enter your choice : "))
if choice == 1:
if len(queue) == ... |
# coding=utf-8
import burro
'''
Created on 31/10/2011
Testado em python 2.6
Interface que dado um numero em binario devolve seus fatores primos.
Espera-se que a entrada esteja correta.
@author: Geraldo
'''
def main():
numero = raw_input("Digite um numero em binario:")
lista = burro.fatoracao_burra(numero)
... |
from collections import defaultdict
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
split_s = s.split(' ')
pat = list(pattern)
if len(split_s) != len(pat):
return False
else:
for i in range(0, len(split_s)):
if split_s.in... |
##
# Zheng, Yixing
# October 11, 2016
# CS 122
#
# A program that prints multiplication table
##
# Defind data fields
n = 10
# Print out multiplication table
for row in range(1, n + 1):
for col in range(1, n+1):
print(row * col)
# The fancy way found online that provides exactly what the question... |
##
# Zheng, Yixing
# October 2, 2016
# CS 122
#
# A program that reads in two float numbers and tests whether they are the same
# up to two decimal places
##
# Get input
float1 = float(input("Enter a floating-point number: "))
float2 = float(input("Enter a floating-point number: "))
# Round two floats to two decimal ... |
##
# Zheng, Yixing
# September 12, 2016
#
# A program that calculates and prints the dew point value
##
# Import log function
from math import log
# Define data field
A = 17.27
B = 237.7
# Get input
relativeHumidity = float(input("Please enter relative humidity (between 0 and 1): "))
if relativeHumidity > 1:
pri... |
# Zheng, Yixing
# CS 122, August, 31, 2016
#
# Integer input
# Getting input in the numbers of gallons of gas in the tank
# And the fuel efficiency in miles per gallon
# And the price of gas per gallon
# And then print the cost per 100 miles and how far the car can go with the gas in tank
# Getting input
gas... |
import unittest
from src.repeated_words import repeated_words
class TestRepeatWords(unittest.TestCase):
def test_equality(self):
test_list = ['cat', 'Cat', 'doG', 'dog', 'COW']
repeated = set(['cat', 'dog'])
self.assertEqual(repeated_words(test_list), repeated)
def test_second_equal... |
def biggest_area(array):
result = 0
for i, height in enumerate(array):
if height == 0:
continue
length = 1
position = i
while position < len(array) - 1:
if array[position + 1] >= height:
length += 1
else:
break
... |
import unittest
from src.very_basic_operations import add, factorial
class AddingTwoNumbersTest(unittest.TestCase):
def test_equality(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(0, 3), 3)
self.assertEqual(add(-1, 3), 2)
class FactorialTest(unittest.TestCase):
def te... |
# Создайте класс Student, конструктор которого имеет параметры name, lastname,
# department, year_of_entrance. Добавьте метод get_student_info, который
# возвращает имя, фамилию, год поступления и факультет в
# отформатированном виде: “Вася Иванов поступил в 2017 г. на факультет:
# Программирование.”
class Student():... |
"""
The main method of the program: opens pygame window and has main loop.
"""
import pygame.locals
import EditWindow
import VisualWindow
from Functions import *
from Constants import WIDTH
from Constants import ROWS
from Constants import DRAW_FUNCS
from tkinter import Tk
from tkinter import messagebox as mb
def main... |
import random
import string
def passwordGenerate(num) :
alph = string.ascii_letters+string.digits
str_password = str().join((random.SystemRandom()).choice(alph) for _ in range(num))
print("The generated password: " + str_password)
num = int(input("Enter a number for the length of the password:")... |
#COMMIT DAMN YOU
#The Map_Object class contains the basic variables and functions that any object placed on the board will need.
class Map_Object:
def __init__(self, x, y, imgpath, Img):
self.xcoordinate = x
self.ycoordinate = y
self.imgpath = imgpath
self.Img= pygame.imag... |
# Time Complexity : O(nlogn)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this :
# Your code here along with comments explaining your approach
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = {}
... |
#POINTS ON A SPHERE - Monte Carlo vs Gradient Flow
#Graphical Output: Initial config, Final config. Graph of energy vs time for monte carlo and gradient flow methods.
import numpy as np
import matplotlib.pyplot as plt
import random
from mpl_toolkits.mplot3d import Axes3D
import time
# project one or all points to th... |
# POINTS ON A SPHERE - Voronoi Regions
# Graphical outputs: voronoi construction for points on a sphere
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def dist(x1,x2):
sum=0.0
for i in range(len(x1)):
sum=sum+(x1[i]-x2[i])**2
return np.sqrt(sum)
#choos... |
"""Problem 9: Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a b c, for which,
a
2 + b
2 = c
2
For example, 3
2 + 4
2 = 9 + 16 = 25 = 5
2
.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc."""
limit = 1000
for i in range(1, limit + 1)... |
"""Problem 21: Amicable numbers
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, ... |
#!/usr/bin/env python3
def read_triangle():
with open("in/p067_triangle.txt") as f:
lines = f.read().strip().splitlines()
triangle = []
for line in lines:
row = list(map(int, line.split()))
triangle.append(row)
return triangle
def max_path(triangle):
# R... |
#!/usr/bin/python3
import primes
# Compute the factors as a dict.
def factor_dict(number):
d = dict()
for f in primes.factors(number):
if f in d:
d[f] += 1
else:
d[f] = 1
return d
# Join all these dictionaries.
lcm_factors = dict()
for number in range(1, 21):
fa... |
# pyhon3 code
def isPalindrome(self, x):
if x < 0 or (str(x)[-1] == '0' and x != 0) :
return False
x = str(x)
y = x[::-1]
return y == x
|
from tkinter import *
from calendar import *
def showCal(y):
# Create a GUI window
new_gui = Tk()
new_gui.geometry('540x600')
# Set the background colour of GUI window
new_gui.config(background = "white")
# set the name of tkinter GUI window
new_gui.title("... |
import random as sysrandom
import string
from flowgram.core.base36 import int_to_base36
# Code modified from http://www.secureprogramming.com/?action=view&feature=recipes&recipeid=20
class SecureRandom(sysrandom.Random):
def __init__(self):
self.useBuiltInRandom = False
self._file = None
s... |
"""
You are given a string . Your task is to swap cases. In other words, convert all
lowercase letters to uppercase letters and vice versa.
"""
def swap_case(s):
Swap_string = ""
for character in s:
if character.isupper() == True:
Swap_string = Swap_string + character.lower()
else:... |
"""
URL: https://www.hackerrank.com/challenges/correlation-and-regression-lines-6/problem
Here are the test scores of 10 students in physics and history:
Physics Scores 15 12 8 8 7 7 7 6 5 3
History Scores 10 25 17 11 13 17 20 13 9 15
Compute Karl Pearson’s coefficient of correlation between... |
import argparse, json
alpha_to_index_mapping = {
"a": 0,
"b": 1,
"c": 2,
"d": 3,
"e": 4,
"f": 5,
"g": 6,
"h": 7
}
index_to_alpha_mapping = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h"
}
"""
def printBoard(chessBoard):
print('------... |
#part 1
def countThe():
infile = open("shakespeare.txt", 'r')
frequencyList = []
for word in ('the', 'The', 'THE'):
frequencyList.append((wordList.count(word), word))
return frequencyList
#part 2
def wordsStartThe():
infile = open("shakespeare.txt", 'r')
adict =... |
"""
1.5: Allow items to be added to menu
"""
# create a dictionary for the menu
add = 'y'
menu = {
'fruit': {
'apples': {
'price': 4
},
'oranges': {
'price': 2
}
},
'vegetables:': {
'carrots': {
'price': 2
... |
"""
4: Box Size
Determine paper or boxes
Work out smallest possible number of a box size
Chose that box size
Large = 20 items
Medium = 10 items
Small = 5 items
"""
# import math library for later calculations
import math
# random order for testing
order = {'apples': {'price': 4, 'quantity': 5}, 'orang... |
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): su... |
# coding:utf-8
# f = open("email.txt")
# str = f.read();
# str1 = "<597234159@qq.com>"
# count = 0;
# temp = []
# len = len(str)
# while count < len:
# if str[count] == '<':
# count+=1
# start = count
# while str[count] != '>':
# count+=1
# end = count
# temp.app... |
import math
import time
import quadratic
import random
def time_it(f, args=None):
t0 = time.time()
print('--- Timed execution for {} ----------------'.format(f.__name__))
print('Running...')
result = f(*args) if args is not None else f()
print('Solution is {}'.format(result))
t1 = time.time()
... |
import eulerlib
def fraction_to_decimal(numerator, denominator):
"""
https://www.geeksforgeeks.org/find-recurring-sequence-fraction/
:param numerator:
:param denominator:
:return:
"""
result = str(int(numerator / denominator))
list_of_previous_remainders = []
remainder = numerator ... |
from math import sqrt
def is_invalid_polynomial(a, b):
return a == 0 and b == 0
def is_first_degree_polynomial(a, b):
return a == 0 and b != 0
def calculate_discriminant(a, b, c):
return b * b - 4 * a * c
def first_degree_solution(b, c):
return -c / b
def negative_solution(a, b, discriminant):... |
import eulerlib
class Fraction:
def __init__(self, num, den):
self.num = num
self.den = den
def __add__(self, other):
if isinstance(other, Fraction):
c = eulerlib.lcm(self.den, other.den)
a = c * self
b = c * other
return Fraction(a.num ... |
def break_words(words):
"""This function will break up words for us"""
return words.split(' ')
def sort_words(words):
"""This function will sort up words for us"""
return sorted(words)
def print_first_word(words):
"""Print the first word for us after popping it up"""
print(words.pop(0))
def p... |
a = [10,20,60,80,20,60]
dup_items = []
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.append(x)
dup_items.sort()
print(dup_items) |
#!/usr/bin/env python
# Sortable Coding Challenge Entry
# February 27, 2012
# Copyright 2012 Steve Hanov (steve.hanov@gmail.com)
#
# Strategy: Use a bayesian classifier to rank the best product choices for each
# listing. Then use a heuristic to pick the best one from this short list.
# Finally, once we have grouped t... |
from math import sin, cos, sqrt, atan2, radians
EARTH_RADIUS_IN_KM = 6373.0
latitude_1 = 52.2296756
longitude_1 = 21.0122287
latitude_2 = 52.406374
longitude_2 = 16.9251681
lat1 = radians(latitude_1)
lon1 = radians(longitude_1)
lat2 = radians(latitude_2)
lon2 = radians(longitude_2)
dlon = lon2 - lon1
dlat = lat2 - ... |
a=1
b=3.45546
v=(2+4j)
print(a,b,v)
#concatination
var1="hello"
var2="world"
print(var2+var1)
#repeat
print(var1 * 4)
#slice operator
print(var2[2:4])
#list
lis=[]
list1=["ab",1,4,45,"y"]
list2=[1,2,3,4,5,6,7]
print(list1)
print(list2)
print(max(list2))
print(min(list2))
print(len(list2))
#
|
def main():
Student = {"name":"zaid","age":24,"slary":20130}
print(Student,type(Student))
print(Student["name"])
print(Student["slary"])
#a new way to dictionary
StudentNew = dict(name="zaid",age=30,slary = 2019)
print(StudentNew)
print(StudentNew['slary'])
print(StudentNew['age']... |
def main():
n = True
while(n):
age = input("enter your age or enter 0 to exit : ")
try:
if(int(age)>=18):
print("welcome")
elif(int(age)>15 and int(age)<18):
print("hi")
elif(int(age)>10):
print("not welcome")
e... |
def main():
word = "python"
word2 = ""
for letter in word:
if(letter=="p" or letter == "t"):
continue
elif(letter == "o"):
break
word2 = word2 + letter
print(word2)
if __name__ == '__main__':main()
|
num1 = 0
num2 = 0
result = 0
def display():
print("{} + {} = {} ".format(num1,num2,result))
def sum(n1,n2):
r = n2+n1
return r
def main():
global num1
global num2
global result
while(True):
try:
num1, num2 = input("enter tow number or any key to exit : ").split()
resu... |
import numpy as np
if __name__ == '__main__':
print('Numpy - Boolean Indexing & Slicing')
words = np.array(['Hi', 'Ho', 'Ha', 'He', 'Hu', 'Ha', 'Ha', 'Hu'])
data = np.array([
np.linspace(0, 10, 10, dtype=np.int16),
np.linspace(10, 19, 10, dtype=np.int16),
np.linspace(20, 29, 10, dt... |
import numpy as np
from numpy.random import *
if __name__ == '__main__':
print('Numpy - Random numbers')
# Return a sample (or samples) from the "standard normal" distribution.
# This is a convenience function for users porting code from Matlab, which wraps `standard_normal`.
print('-----\nrand funct... |
# Arithmetic operators on arrays apply elementwise.
# A new array is created and filled with the result.
import numpy as np
from array_creation import ones
def arithmetic_operations(array1, array2, operation: ''):
"""
Arithmetic operations are possible:
1. only between arrays with the same number of eleme... |
import numpy as np
from math_study.numpy_basics.data_types.data_types_list import data_type, table_of_data_types
def print_info(_array: np.array):
print('{} \n\t 1. dtype = {}\n\t 2. item size = {}\n\t 3. n° of bytes = {}\n'
.format(_array, _array.dtype, _array.itemsize, _array.nbytes))
def create_ar... |
a = int(input())
m = []
while a > 0:
m.append(a)
a = int(input())
print('%.2f' % (sum(m) / len(m)))
|
import math
tetha = input ('Please Enter the angle in DEG : ')
tethaForOut = tetha
tetha = float (tetha)
tetha = (tetha * math.pi) / 180
out = (math.sin(tetha) ** 2) + (math.cos(tetha) ** 2)
print ('Sin^2 (' + str(tethaForOut) + ') + Cos^2 (' + str(tethaForOut) + ') = ' + str(out))
|
'''
Created on 2018年1月31日
@author: 陈佳文
'''
'''
创建列表
'''
listName = [1.1,3,'上海','深圳']
listShow = ['aaa','bbb']
'''添加数据'''
listName.extend(listShow)
listName.append('小蜗')
listName.insert(2, '北京')
print(999)
'''删除数据2种方法'''
listName.pop(2)
listName.remove('bbb')
print(listName)
'''统计列表值的数量'''
p... |
from display import *
from matrix import *
def draw_lines( matrix, screen, color ):
for i in range (0,len(matrix[0]), 2):
draw_line(matrix[0][i], matrix[1][i],matrix[0][i+1], matrix[1][i+1],screen,color)
def add_edge( matrix, x0, y0, z0, x1, y1, z1 ):
add_point(matrix, x0, y0, z0)
add_point(matri... |
def add2(num1,num2):
s=num1+num2
return s
def add3(num1,num2,num3):
s=num1+num2+num3
return s
def add4(num1,num2,num3,num4):
s=num1+num2+num3+num4
return s
print add2(3,4)
print add3(1,2,3)
print add4(1,2,3,4)
|
def howSumHelper(lst, target, stk, table):
if target in table:
return list(table[target])
if target == 0:
return stk
if target < 0:
return []
for num in lst:
rem = target - num
stk.append(num)
if howSumHelper(lst, rem, stk, table):
table[t... |
# In this problem, we take a target, and return a combination of numbers array.
# Return the operands which sum to target.
def howSumHelper(lst, target, stk):
if target == 0:
return stk
if target < 0:
return None
for num in lst:
rem = target - num
stk.append(num)
... |
from Atom import Atom
from Walker import Walker
import numpy as np
def dmc(state, trial_energy, timestep = 1e-3, importance = False):
"""A function to perform one diffusion step in diffusion Monte Carlo, or DMC.
Arguments:
state {Atom} -- The previous state of the of the atom simulation.
t... |
import oop
class User:
def __init__(self, _name, _surname, _username, _password):
# attribute
self.name = _name
self.surname = _surname
self.username = _username
self.password = _password
def showUserData(self):
print(f"Name : {self.name}, Surname : {se... |
"""Class for problem
Author: Zoïs Moitier
Karlsruhe Institute of Technology, Germany
"""
from dataclasses import dataclass
from enum import Enum, auto
from math import atanh, sqrt
from typing import Tuple
from .ellipse_parametrization import EllipseParametrization
class BoundaryType(Enum):
"""Enum ... |
""" Compute analytic solution for laplace
Author: Zoïs Moitier
Karlsruhe Institute of Technology, Germany
"""
from numpy import cos, sin
from sympy import lambdify, symbols
def laplace_sol_eve(m: int, ε: float):
"""
scr, sol = laplace_sol_eve(m, ε)
Return the even source term and soluti... |
# Режим сна
# A = int(input())
# B = int(input())
# H = int(input())
# if H < A:
# print("Недосып")
# elif H > B:
# print("Пересып")
# else:
# print("Это нормально")
# Високосный ли год
# A = int(input())
# if A % 4 == 0 and A % 100 != 0:
# print("Високосный")
# elif A % 400 == 0:
# print("Високосн... |
#StringManipulation.py
# Script to manipulate string values and
str = 'nagavenkata navlam'
print(str)
print(str[0])
print "substring"+str[2:]
print str*2
print str[2:9]
#list manipulation
list = ['abcd',786, 2.23, 'john']
#print the list details
print list
print list[... |
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
print("\nWelcom to RSA IMPLEMENTATION\n")
p = int(input('Enter the value of p = '))
q = int(input('\nEnter the value of q = '))
String = input('\nEnter the value of text = ')
l=[]
ciphertextlist =[]
deciphertextlist=[]
for i in String:
l.appe... |
import turtle
UP_ARROW="Up"
LEFT_ARROW="Left"
DOWN_ARROW="Down"
RIGHT_ARROW="Right"
SPACEBAR="space"
UP=0
DOWN=1
LEFT=2
RIGHT=3
direction=UP
def up():
direction=UP
turtle.forward(50)
print("you moved up ")
def down():
direction=DOWN
turtle.backward(50)
print("you moved DOWN ")
d... |
#!/usr/bin/env python
# coding: utf-8
# In[5]:
#Write a Python program to convert kilometers to miles?
km=input("Enter kilometres:")
miles= 0.621371192 * int(km)
print(miles,"miles")
# In[8]:
#Write a Python program to convert Celsius to Fahrenheit?
celsius=input("Enter celsius degree:")
far= ((9/5) * float(cels... |
####################################################################
# Lab 7: BioPython
# This script reads the MAOA genbank file that we have
# seen previously in Lab 5. Here, you will use BioPython
# to answer some of the questions you had answered in
# the previous lab. Biopython must be used to answer the question... |
from io_parser import IOParser
# video io
from videoreader import VideoReader
from videowriter import VideoWriter
# OpenCV
import cv2
# numpy
import numpy as np
if __name__ == '__main__':
parser = IOParser()
reader = VideoReader(parser.input_file)
writer = VideoWriter(parser.output_file, reader.fps, (re... |
import string
def letter_code(source, letter, key, cezar):
source=source
if (source.index(letter)+key)<len(source):
cezar+=source[source.index(letter)+key]
else:
cezar+=source[source.index(letter)+key-len(source)]
return cezar
def cezar_code(text, key):
alpha_upper = string.ascii_uppercase
al... |
# STRETCH: implement Linear Search
def linear_search(list, target):
for i in range(len(list)):
if list[i] == target:
return i
return -1 # not found
# STRETCH: write an iterative implementation of Binary Search
def binary_search(list, target):
if len(list) == 0:
return -1 #... |
## Problem 2: (https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
# Time Complexity : O(logn)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: we use binary search method to reduce the time complexity of traversin... |
def NOD (a,b):
while a != 0 and b != 0 :
if a>b:
a = a % b
else:
b = b % a
return a+b
a = -1
b = -1
while a<0 or b<0:
a = float(input("a = "))
b = float(input("b = "))
print("NOD = %d" %(NOD(a,b))) |
def calc(expression):
operator = []
operands = []
result = []
for item in expression:
math_sign = ['+', '-', '*', '/']
assert expression[0] in math_sign, 'Операции не найдено!'
try:
if item.isalpha():
raise AssertionError
except AssertionError:... |
# Generate sensor data randonlu in time intervals of 3 seconds
# Keep generating this data
import time
from datetime import datetime
from random import *
import os
def data_generator():
# Generate data inside the data folder
f = open("data/sensor2.txt", "a", os.O_NONBLOCK)
while(1):
data = round(u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.