text stringlengths 37 1.41M |
|---|
class BinarySearchTree():
def __init__(self,root=None,*initial_keys):
self.root = None if root == None else Node(root)
if not initial_keys:
return
for key in initial_keys:
self.insert(key)
def insert(self,key):
new_node = Node(key)
if not self.root:
self.root = new_node
self.r... |
# 03) Agora, teste N = 100.
# Em media quantas iteracoes sao necessarias para que o PLA convirja para N = 100 pontos de treinamento?
# Informe o valor mais proximo ao seu resultado.
# a) 50; b) 100; c) 500; d) 1000; e) 5000
import random
import matplotlib.pyplot as plt
import numpy as np
#There's an unknown Target ... |
arr = input('')
arr = arr[1:len(arr)-1]
l = []
if ", " in arr:
l = arr.split(", ")
else:
l = arr.split(",")
l.sort(reverse = True)
arr = ''.join(l)
op = ''
c = 0
for i in arr:
op = op + i
c = c + 1
if c == 3:
op = op + ','
c = 0
if op.endswith(","):
op = op[:len(op)-1]
print(op)
|
"Algoritmo Cryptografico de Transposicion por Series"
"Cristian Camilo Riano cristianriano@unicauca.edu.co"
"Diego Alejandro Alvis diegoalvis@unicauca.edu.co"
"9256...3ae0"
import sys
def cifrar(frase, serie):
cryptograma=''
for n in serie:
cryptograma=cryptograma+frase[n-1]
return cryptograma
def stuff(frase,... |
import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
Reads in the two datasets, one for the messages and one for their
categories, and combines them into one DataFrame.
INPUTS:
messages_filepath: str. A file path fo... |
import collections
class Cell:
# Constructs the Cell
def __init__(self, row, col):
self.__tuple = (row, col)
self.__valList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Checks if the value is contained in the value list
def contains(self, val):
return val in self.__valList
# Gets the ... |
user_seconds=int(input("Enter the seconds you want to convert"))
seconds_into_days=user_seconds/(60*60*24)
seconds_into_hours=user_seconds/(60*60)
seconds_into_minutes=int(user_seconds/60)
seconds_into_seconds=user_seconds
print(f"the number of day in that seconds is:{seconds_into_days}days\n and hours is:{seconds_into... |
''' #Write a python program to find the max of three numbers.'''
def maxnumber(one,two,three):
if one>two and one>three:
print("the first number is maximum")
elif two>one and two>three:
print("the second number is greater")
else:
print("the third number is greater")
first_number=in... |
''' Write a function called showNumbers that take a parameter called limit. It should print all the numbers between 0
and limit with a label to identify the even and odd numbers. For example, if the limit is 3, it should print
0 Even
1 Odd
2 Even
'''
def showNumbers (limit):
if (limit%2==0):
print(f'It is ... |
d=int(input("How far did you travel today (in miles)? "))
t=int(input("How long did it take you (in hours)? "))
s=d/t
print(f'your speed was {s} miles per hour') |
# Function having no parameter and no return type.
def add():
a = 6
b = 4
print(a + b)
add()
# Function having parameter and no return type.
def sub(a,b):
print(a-b)
sub(6,4)
# Function having no parameter and with return type.
def mul():
a = 10
b = 2
return a*b
product = mul()
print(prod... |
def mul(n):
if n==1:
return 3
else:
return 3+mul(n-1)
for i in range(1,11):
print(mul(i)) |
import random
my_list = []
a = 0
while a<=50:
num = random.randint(1, 200)
if num % 2 ==0:
print(my_list.append(num)) |
'''Price of a house is $1M. If a buyer has good credit, they need to put down 10% otherwise they need to
put down 20%. Print down the payment.'''
price_of_house=1000000
down_payment=input("choose if you have good credit or not?\n")
if(down_payment=="good credit"):
print((f"the amount after good credit={10/100*10000... |
class HouseItem:
def __init__(self,new_name,new_area):
self.name = new_name
self.area = new_area
def __str__(self):
return '{}占地面积为:{}'.format(self.name,self.area)
bed = HouseItem('席梦思',4)
chest = HouseItem('衣柜',2)
table = HouseItem('餐桌',1.5)
class House:
def __init__(self,house_type... |
class Person:
def __init__(self,new_weight,new_name):
self.weight = new_weight
self.name = new_name
def run(self):
self.weight -= 0.5
print('{}的体重是{}'.format(self.name,self.weight))
def eat(self):
self.weight +=1
print('{}的体重是{}'.format(self.name,self.weight))... |
a = int(input('输入一个数a:\n'))
b = int(input('输入一个数b:\n'))
print('a=%d'%b+'b=%d'%a)
|
import networkx as nx
import matplotlib.pyplot as plt
#import csv
#Data = open('graph.txt', "r", encoding='utf8')
#read = csv.reader(Data)
#G=nx.DiGraph() # use net.Graph() for undirected graph
#G = nx.read_edgelist(read, create_using=Graphtype, nodetype=str, data=(('weight',float),))
#G = nx.read_edgelist('graph... |
#program to transpose a matrix
X = [[1,2],
[3,4],
[5,6]]
result = [[0,0,0],
[0,0,0]]
#iterate through rows
for i in range(len(X)):
#iterate through cilumns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r) |
'''
from random import randint
steps = 7
one_count = 0
two_count = 0
ongoing = steps
reached = False
while reached == False:
goto = randint(1,2)
if goto == 1:
one_count += 1
if goto == 2:
two_count += 1
ongoing = ongoing - goto
if ongoing == 0:
reached = True
print('Reache... |
class Enemy:
life = 3
def attack(self):
print('Ouch!')
self.life -= 1
def checkLife(self):
if self.life <= 0:
print("I am dead")
else:
print(str(self.life) + ' life left')
enemy1 = Enemy() # enemy1 is an Object
enemy2 = Enemy()
enemy1.attack()
ene... |
# -*- coding: utf-8 -*-
from sample import _
from package import side
def runModule():
print(_('Hello world'))
numb1 = 1
numb2 = 2
#Former format string: 'This is a formatted string: %2d %d' % (numb1, numb2)
#For translated strings: use keys or at least indexes for translaters to change position of replaced str... |
def mystery(num):
if num == 10:
num = num * 10
elif num == 30:
num = num * 30
else:
num = num
return num
num = 10 * 3
print( mystery(num) )
|
import argparse
import re
def get_args():
'''Gets the arguments from the command line.'''
parser = argparse.ArgumentParser("Run the script on an input file")
# -- Create the descriptions for the commands
i_desc = "The location of the input file"
o_desc = "The location where to output the file"
# -... |
me = {
'name': 'Vero',
'age': 25,
'pet': 'Mina',
'job': 'SE',
'languages': ['German', 'French', 'Spanish', 'English']
}
# print me.items()
def dict_stuff(dct):
for key, item in dct.items():
print 'my ', key, ' is ', item
dict_stuff(me)
|
class Solution:
def isValid(self, s: str) -> bool:
st = []
close = {
')': '(',
'}': '{',
']': '['
}
for c in s:
if c in close:
if len(st) == 0:
return False
if st.pop() != close[c]:
... |
from TreeNode import TreeNode as Node
class Tree:
# constructor
def __init__(self):
self.root = None
# create a new node
def createNode (self, val):
node = Node()
node.setVal(val)
return node
def preOrderTraversal (self, root):
if root == None:
return
print root.getVal()," ",
self.preOrderTrav... |
from TreeNode import TreeNode as Node
class Tree:
def __init__(self):
self.root = None
def createNode(self, val):
node = Node()
node.setVal(val)
return node
def preOrderTraversal(self, root):
if root == None:
return
print root.getVal()," ",
self.preOrderTraversal(root.getLeftChild())
self.preOr... |
from TreeNode import TreeNode as Node
class Tree:
def __init__ (self):
self.root = None
def createNode (self, val):
node = Node()
node.setVal(val)
return node
def lca (self, current, first, second):
"""
Since, this is a BST, key comparison was possible.
See next question for LCA in Binary Tree.
... |
from listNode import Node
class List:
def __init__(self):
self.head = None
def getHead(self):
return self.head
def setHead(self, head):
self.head = head
def createNode(self, val):
node = Node()
node.setVal(val)
return node
def printList(self):
... |
from TreeNode import TreeNode as Node
class Tree:
def __init__(self):
self.root = None
def createNode(self, val):
node = Node()
node.setVal(val)
return node
def nodesAtLevelK (self, current, k):
if current is None:
return
if k == 0:
print current.getVal()," ",
self.nodesAtLevelK(current.getLe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
N1 = 13
N2 = 15
N3 = 17
print("1.")
def isPrime1(N):
for i in range(2, N):
if N % i == 0:
return False
return True
print(str(N1) + ":" + ("OK" if isPrime1(N1) else "NG"))
print(str(N2) + ":" + ("OK" if isPrime1(N2) else "NG"))
prin... |
#Import Python modules for handling csv
import sys
import csv
import operator
#Open phonebook.csv file
with open("phonebook.csv", "rU") as myfile:
checkreader = csv.reader(myfile)
header = next(checkreader)
sorted_data = sorted(checkreader, key = operator.itemgetter(1))
with open("dileepPhoneBook.csv", "wb"... |
"""
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
If there is no solution possible, return -1.
Example :
A : [3 5 4 2]
Output : 2
for the pair (3, 4)
"""
class Solution:
@staticmethod
def max_distance(arr):
n = len(arr)
l_arr = [None]... |
"""
Given a number N, return number of ways you can draw N chords in a circle with 2*N points such that no 2 chords
intersect.
Two ways are different if there exists a chord which is present in one way and not in other.
For example,
N=2
If points are numbered 1 to 4 in clockwise direction, then different ways to draw... |
"""
You are given an array of N integers, A1, A2 ,…, AN and an integer K. Return the of count of distinct numbers in all
windows of size K.
Formally, return an array of size N-K+1 where i’th element in this array contains number of distinct elements in
sequence Ai, Ai+1 ,…, Ai+k-1.
Note:
If K > N, return empty array... |
"""
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
int isMatch(const char *s, const char *p)
Some examples:
is... |
"""
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->6->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
"""
from Python.Level4.LinkedList import Node, Traverse
class Solution:
def reverse_list(self, head, m, n):
diff, dummy, cur = n - m ... |
"""
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
Note that all the operations have to be constant... |
"""
Given a binary tree, print a vertical order traversal of it.
Example :
Given binary tree:
6
/ \
3 7
/ \ \
2 5 9
returns
[
[2],
[3],
[6 5],
[7],
[9]
]
Note : If 2 Tree Nodes shares the same vertical level then the one with lesser depth will come first.
"""
f... |
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
NOTE : The path has to end on a leaf node.
Example :
1
/
2
min depth = 2.
"""
from Python.Level6.TreeDataStructure import Nod... |
"""
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water
it is able to trap after raining.
Example :
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Rain water trapped: Example 1
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
In ... |
"""
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Also, the subsets should be sorted in ascending ( lexicographic ) order.
The list is not necessarily sorted.
Example :
If S = [1,2,3],... |
"""
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, … , ak... |
"""
You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Note that in your output A should pre... |
"""
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
"""
from Python.Level4.LinkedList import Node, Traverse
class Solution:
# @param A : head node of linked list
# @return the head node i... |
"""
Given a positive integer N, print all the integers from 1 to N. But for multiples of 3 print “Fizz” instead of the
number and for the multiples of 5 print “Buzz”. Also for number which are multiple of 3 and 5, prints “FizzBuzz”.
Example
N = 5
Return: [1 2 Fizz 4 Buzz]
Note: Instead of printing the answer, you hav... |
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# class Solution3:
# # @param a list of ListNode
# # @return a ListNode
# def mergeKLists(self, lists):
# import heapq
#
# dummy = ListNode(0)
# current = dummy
#
# he... |
# coding=utf-8
"""
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1)
You begin the journey with an empty tank at one of the gas stations.
Return the m... |
"""
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
The digit 0 maps to 0 itself.
The digit 1 maps to 1 itself.
Input: Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd... |
"""
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers % 1003.
Example :
1
/ \
2 3
The root-to-leaf path 1->2 represents the numbe... |
"""
Given an array A of integers, find the index of values that satisfy A + B = C + D, where A,B,C & D are integers values
in the array
Note:
1) Return the indices `A1 B1 C1 D1`, so that
A[A1] + A[B1] = A[C1] + A[D1]
A1 < B1, C1 < D1
A1 < C1, B1 != D1, B1 != C1
2) If there are more than one solutions,
then ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 17 17:16:53 2018
@author: carlosponce
"""
def findAnEven(L):
"""Assumes L is a list of integers
Returns the first even number in L
Raises ValueError if L does not contain an even number"""
for i in L:
if i % 2 == 0:
... |
import random
import os
import sys
# File I/O / File Handling
test_file = open("test.txt", "wb") ##Opens the file if creaated/not created in write mode
print(test_file.mode) ##Print the mode of file opened
print(test_file.name) ##Print the name of the file opened
test_file.write(bytes("Write me to the file\n", ... |
def avg(l):
# calculate the sum of the items
sum = 0
for item in l:
sum = sum + item
# divide by the number of items
average = sum / len(l)
return average
def sum_of_squares(l):
sum = 0;
for item in l:
sum = sum + item*item
return sum
grades = [90,95,100,9... |
# read in the entire file
# as a big string of characters
# f = open("data.dat")
# data = f.read()
# each time we do f.readline()
# we read in the next line
# line = f.readline()
# print(line)
# f.seek(0)
# line = f.readline()
# print(line)
f = open('data.dat')
data = f.read()
words_from_data = data.split()
lines... |
import numpy as np
class StructuredEncoder(object):
"""
In structured prediction problems we often
manipulate abstract output structures such as sequences, graphs,
and trees. These structures come from a set :math:`{\cal Y}(x)`
dependent on an input structure :math:`x`.
In order to work with t... |
import pymatrix #used throughout the program - have to use this instead of numpy because of Brython (browser implementation) support
import math #used throughout the program
import random #Used in multiple places, most prominently when generating a random key matrix
from random import randint #Used in multiple places,... |
"""
countdata.py
Functions for stats and analysis of count data.
"""
import sys
import numpy as np
import scipy as sp
# import scipy.stats
# ==============================================================================
# ======================
# = Count manipulation =
# ======================
def sample2counts(... |
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
class Solution:
def extract_graph(self, graph: dict, node: 'Node'):
graph[node.val] = []
for n_ in node.neighbo... |
# Program to filter which movies you can watch based on inputted age.
# This is the input for the user.
age = int(input("Please enter your age: "))
# This block of code will print a message if the user is over 100
if age >= 100:
print("Wooow, you are {}, you can do whatever you want".format(age))
# This block of c... |
# What is a function?
# Why should we use a function
# What is the benefit - REUSABLE block of code
# D R Y - Do Not Repeat Yourself
# What functions have we used so far? - print(), type(), str(), int()
# Syntax: def name_of_function with () and :
# Create a function to greet
# def greeting():
# return "Hello... |
class Celsius(object):
def __init__(self, temperature=0):
self.set_temperature(temperature)
def to_fahrenheit(self):
return float(self._temperature) * 1.8 + 32
def get_temperature(self):
return self._temperature
def set_temperature(self, value):
if value < -273:
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 11:46:53 2017
@author: yaojie
"""
n = 3
A = [i for i in range(n, 0, -1)]
B = []
C = []
count = 0
def move_disks(n, src, to, aux):
#Step 1: If h>1 then first use this procedure to move the h−1 smaller disks from peg A to peg B.
#Step 2: N... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 6 09:49:30 2017
@author: yaojie
"""
from functions import is_larger, letter_grade, list_sum, minmax_in_list, is_palindrome, list_sum_newbie
print is_larger(2 , -1)
print is_larger(-1 , 2)
print is_larger(2 , 2)
print ''
for mark in [102,100,83,7... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 6 09:48:34 2017
@author: yaojie
"""
def is_larger(n1, n2):
return n1 > n2
def letter_grade(mark):
if type(mark) == int and mark <= 100 and mark >= 0:
grade = 'E'
if mark >= 90:
grade = 'A'
elif mark >= ... |
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state(): # starting 3x3 board
return [[EMPTY, EMPTY, EMPTY] for i in range(3)]
def player(board):
# Returns player who has the next turn on a board.
return X if sum(x.count("X") for x in board) == sum(x.count("O"... |
import ply.lex as lex
tokens = ['NEWLINE', 'NAME','NUMBER','PLUS','MINUS','TIMES','DIVIDE', 'EQUALS', 'ASIGN' ]
t_ignore = ' \t'
t_NEWLINE = r' \n'
t_PLUS = r'SUMA'
t_MINUS = r'RESTA'
t_TIMES = r'MULTIPLICACION'
t_DIVIDE = r'DIVISION'
t_ASIGN = r'ASIGNACION'
t_EQUALS = r':='
def t_NUMBER(t):
r'\d+'
t.value = ... |
# 4. Crie uma função que recebe a lista de cidades do exercício 2 e que exibe somente as cidades com mais
# de 7 letras na composição do seu nome.
def exercicio4(cidades):
for cidade in cidades:
if(len(cidade) >= 7):
print(cidade) |
def mostraCidade(listaCidades):
for umaCidade in listaCidades:
print(umaCidade)
def adicionarCidadeLista(listaCidades):
cidade = input(
"informe o nome da cidade que você deseja adicionar na coleção: ")
listaCidades.append(cidade)
def main():
listaCidades = []
qtsCidades = int(in... |
# 10. Considere o seguinte dicionário:
# dicio = {"name": "César Lattes", "country": "Brasil", "born": 1924, "role": "Físico"}
# Crie uma função que receba este dicionário e imprima a seguinte saída (sem a borda ao redor):
# Nome do Pesquisador: César Lattes
# País: Brasil
# Ano de Nascimento: 1924 – Profissão: Físico... |
#Crie uma função, que utilizando um desvio condicional retorne true se o valor
# for negativo e falso se ele for positivo
def verificarValorNegativo(valor):
if(valor < 0):
return True
else:
return False
def exibeNomeCompleto(nome, sobrenome):
print(nome + sobrenome)
verificarValorNegativ... |
num = int(input("Digite um número: "))
if num % 2 == 0 or num % 3 == 0:
print("O número é divisível por 2 ou 3")
else:
print("O número não é divisível por 2 ou 3")
|
### Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. ###
def main():
str1 = input("Enter the 1st string :")
str2 = input("Enter the 2nd string :")
print(checkForPermutability(str1, str2))
def checkForPermutability(str1, str2):
sorted_str1 = sorted(st... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#插入排序,从小到大
#时间复杂度O(n²)
list=[5, 0, 8, 1, 10, 13, 18, 19, 9, 11]
def insertion_sort(list):
length=len(list)
for i in range(1,length):
current=i
position=i-1
while list[current]<list[position] and position>=0:
list[current],list[posi... |
def count_string(string):
s=0
for letter in string:
letter=1
s=letter+s
return s
print (count_string("Jona")) |
"""
find_parity_outliers
Given a list, returns the items that are parity outliers.
Use collections.Counter with a list comprehension to count even and odd values in the list, use collections.Counter.most_common() to get the most common parity. Use a list comprehension to find all elements that do not match the most c... |
import numpy as np
class Transaction(object):
"""
Handles the transaction of an asset, as used in the
Position class.
Parameters
----------
asset : `str`
The asset symbol of the transaction
quantity : `int`
Whole number quantity of shares in the transaction
dt : `pd.Ti... |
class color:
'''
Inialization for the premade colors.
Values are being set in the constructor
'''
global black, white # Non colors
global red, green, blue # Primary colors
global yellow, violet, orange # secondary colors
global pink, brown, cyan, gray # The rest of the colors
... |
import random
with open("words.txt") as f:
words = f.read().split()
correct_letters = set()
wrong_letters = set()
selected_word = random.choice(words)
def lost():
return len(wrong_letters) == 8
def won():
return all([letter in correct_letters for letter in selected_word])
def complete():
return won... |
# File: q4.py
# Author: Brittany Vamvakias
# Date: 02/20/2020
# Section: 501
# E-mail: brittvam@tamu.edu
# Description: This code asks for the starting and ending value for a Fibonacci seqeunce. The sequence is then created until the final value is greater than or equal to the ending value. The sequence is then printed... |
#Write a program to accept a number and determine whether it is a prime number or not.
n=int(input("Enter the value of n:")
if n<2:
print(f"{n} is not prime")
else:
for i in range(2,n/2):
if n%i==0:
print(f"{n} is a prime number")
else:
print(f"{n} is not prime numb... |
# PyParagraph Exercise for UCB Extension Data Science Bootcamp, HW3
# Written by A. Lam
## Modules
import os
import csv
import re # for sentence splitting over multiple punctuation signs
import string # for complete punctuation list
# Prompt for filename
# sourceFile = input('Please input the source filename and exte... |
from math import sqrt
"""
Prime Number Detector
"""
def is_prime(x):
if x<2:
return False
for i in range(2, int(sqrt(x))+1):
if x % i == 0:
return False
return True
def main():
while True:
inp = input("Give me a number to see if it is Prime: ")
try:
... |
import random
guesses = []
def load_word():
f = open('words.txt', 'r')
words_list = f.readlines()
f.close()
words_list = words_list[0].split(' ')
secret_word = random.choice(words_list)
return str(secret_word).rstrip()
super_secret_word = load_word()
blank_list = list('-' * len(super_secret_w... |
import math
import os
import random
import re
import sys
# Complete the twoStrings function below.
#takes in two strings s1 and s2. Returns yes if there exists a common substring else, no.
#strings are alphabetic a-z lengths of s1 and s2 can be 10^5 length
#substring can be length 1
def twoStrings(s1, s2):... |
import turtle
import math
bob=turtle.Turtle()
#--------------------------------------------------
def OlympicCircle():
for i in range(circside):
bob.fd(circ/36)
bob.lt(360/circside)
def OlympicRings():
bob.reset()
bob.pensize(10)
for i in range(3):
bob.penup()
... |
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
min = 10
max = 10
smallestNumber = 999999999
#for i in range(min,
i = min
def getPrimeNumbers(upperBound):... |
### helper function
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
a = 0
b = 0
# since arrA and arrB already sorted, we only need to compare the first element of each when merging!
for i in range( 0, elements ):
if a >= len(arrA): # all eleme... |
# 名称:服务器处理程序
# 时间:20200128
# 作者:voyager
# 功能:计算地点之间的两两距离
# 注意:
import numpy as np
def dist_count(place_loc, place_num):
place_dist = np.zeros((place_num, place_num))
for i in range(place_num):
for j in range(place_num):
place_dist[i, j] = np.sqrt(np.square(place_loc[i, 0] - place_loc[j, 0]... |
#
# @lc app=leetcode.cn id=58 lang=python
#
# [58] 最后一个单词的长度
#
# https://leetcode-cn.com/problems/length-of-last-word/description/
#
# algorithms
# Easy (29.16%)
# Total Accepted: 22.5K
# Total Submissions: 76.7K
# Testcase Example: '"Hello World"'
#
# 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
#
# 如果不存在最后一个单词,请返回 0 。... |
def findWords(words):
ans = []
keyset = ['qwertyuiop', 'asdfghjkl','zxcvbnm']
for key in keyset:
for word in words:
line = set(word.lower())
if line.issubset(set(key)):
ans.append(word)
return ans
if __name__ == "__main__":
words = ["Hello", "Alaska"... |
#!/usr/bin/env python
#This program computes the largest palindrome made from the product
#of two 3-digit numbers
def check_palin(num):
#This function checks if a number is a palindrome
num_str = str(num) #convert the number to a string
num_str = num_str[::-1] #reverse the string
if num == int(num_str):
return ... |
#Assignme: Filter by Type
def compare_Type_Value(data_input):
if(type(data_input)) == int:
if(data_input >= 100):
print "That's a big number!"
else:
print "That's a small number."
elif (type(data_input) == str):
if(len(data_input)>=50):
print "Long sen... |
#print even and odd numbers
def odd_even():
for i in range(2001):
if(i%2==0):
print "Number is " + str(i) + ". This is an even number"
else:
print "Number is " + str(i) + ". This is an odd number"
odd_even()
#print the list by multiplying by n
def list_Multiplier(arr, n):... |
from Teacher import *
class student(Teaher):
print('I\'m the student class')
try:
def get_into(self):
s_user= str(input('Enter your username : '))
for k, v in self.student_info.items():
if k == s_user:
print('+----------------------+')
... |
from module import Module
def sigmoid(x):
return 1/(1 + x.mul(-1).exp())
class Sigmoid(Module):
def __init__(self):
super(Sigmoid, self).__init__()
self.x = 0
def forward(self, x):
self.x = x
return sigmoid(self.x)
def backward(self, grad):
... |
# -*- coding: utf-8 -*-
class Type(object):
def __init__(self, key, size):
self.key = key
self.size = size
self.expr = key.split()
for i in range(0, len(self.expr)):
if self.expr[i] == 'int' and len(self.expr) != 1:
self.expr[i] = r'\(int|\B\)'
... |
radius = float(input())
print("A=%.4f" % ((radius * radius) * 3.14159))
|
print("##Important Numbers##")
print("Plz enter one number addition in range \n like i need table of 2 until 10 i will enter 11")
def table(x,y):
for i in range(1 ,y):
print(x, "x" , i , "=" , x*i)
a=int(input("Enter a number for table = "))
b=int(input("Enter a range of table = "))
table(a,b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.