text stringlengths 37 1.41M |
|---|
#! /usr/bin/env python
#coding=utf-8
#
#215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
#
#What is the sum of the digits of the number 21000?
from __future__ import print_function
from __future__ import division
print(sum(int(s) for s in str(2**1000)))
|
fname=input('Enter file name:')
fil=open(fname)
for line in fil:
print(line.upper().rstrip()) |
from cmd import Cmd
class Child(Cmd):
prompt = 'child> '
#constructor
def __init__(self):
"""
super() accessing inherited methods from a parent class
"""
super(Child, self).__init__()
def do_q(self, args=True):
raise SystemExit
def do_display(self, args=... |
from abc import ABC,abstractmethod
# Another exemple of subclasses
class Employee(ABC):
def __init__(self,rank=None):
self.currentcall = None
self._rank = rank
def isfree(self):
return self.currentcall == None
class Director(Employee):
def rankdirector(self):
self... |
def climbingLeaderBoard(scores, alice):
scores = list(set(scores))
scores.sort(reverse = True)
i = 0
res = []
while(i < len(alice)):
j = 0
while((j < len(scores)) and (scores[j] > alice[i])):
j += 1
res.append(j + 1)
i += 1
retu... |
import math
import os
import random
import re
import sys
def diagonalDifference(arr):
res = [0, 0]
i = 0
j = 0
len_arr = len(arr)
while (i < len_arr):
while (j < len_arr):
res[0] = res[0] + arr[i][j]
res[1] = res[1] + arr[i][len_arr - 1 - j]
i += 1
... |
num = input('Enter a number: ')
total = 0
for x in num:
total += int(x)
print('The sum of the numbers is [' + str(total) + ']')
|
#!/usr/bin/env python3.7.2
from tkinter import *
win = Tk()
win.title('Calculator')
#//win.geometry('400x400')
# ---ELEMENTS---
click1 = Button(win, text='1', width=9, height=4, highlightbackground='orange')
click2 = Button(win, text='2', width=9, height=4, highlightbackground='orange')
click3 = Button(win, text='3',... |
'''
Created on Dec 15, 2016
@author: anand
'''
def isPalindrome(x):
"""
:type x: int
:rtype: bool
"""
if x<0: return False
otherNumber = 0
bkp = x
pwr = -1
while bkp>0:
bkp/=10
pwr+=1
bkp = x
while bkp > 0:
otherNumber += (bkp%10)*... |
'''
'.' 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:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") => false
isMatch("aa","aa") => true
isMatch("aaa","aa... |
'''
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
'''
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[st... |
'''
Given a string s, find the longest palindromic substring in s.
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
'''
def longestPalindrome(s):
"""
:type s: str
:rtype: str
"""
lowLimit = 0
highLimit = len(s)
palindrome = ''
for index in range(0,highLimit):... |
def fatorial(n):
fat=1
while n>1:
fat=fat*n
n=n-1
return fat
|
fraction = ''
i = 0
while len(fraction) < 1000000:
fraction += str(i+1)
i += 1
print(len(fraction))
product = 1
index = [1,10,100,1000,10000,100000,1000000]
for i in range(0,len(index)):
print(int(fraction[index[i]-1]),index[i])
product *= int(fraction[index[i] - 1])
print(product)
|
import math
from problem64 import count_period
from problem64 import continued_fraction
"""
Diophantine equation (unoptimal solution)
f (x,y,D) = x^2 - Dy^2 = 1
ex.
when D = 13
minemal solution in x, where x is an positive integer
is x = 649 and y = 180
rearragning the equation to give an expression for x in terms ... |
#! /usr/local/bin/python3
import functions
def main():
conn, cur = functions.connect()
status = True
functions.print_menu()
while status:
choice = int(input('Choice: '))
if choice == 1:
functions.create_table(conn, cur, 'teachers')
elif choice == 2:
func... |
import locale
from reloj import Reloj
locale.setlocale(locale.LC_ALL, '')
def menu():
print("Estas son las oparaciones que se pueden realizar: ")
print("1- Ver la hora en Greenwich.")
print("2- Ver la fecha y la hora en Greenwich.")
print("3- Ver la fecha y la hora en Nueva York.")
print("4- Ver... |
year=[1,2,4,4,5,5,6,1,23,5,1,2,456,3,12]
pop=[31,4,12,54,1,24,5,23,5,1,5,63,6,23,63]
# Print the last item from year and pop
#year.sort()
#pop.sort()
#print(year[-1])
#print(pop[-1])
# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
import math
v=[]
v2=[]
for i in range(2000,3000,4):
v.append(math... |
import os
import json
import re
class User:
def __init__(self, username, password=None):
self.username = username
self.password = password
def add_account(self): # treba dodati pogoje za dobro geslo in username
with open(os.path.join(os.getcwd(), "database", "accounts.json"), "r+") ... |
# Implementation of Mergesort.
#
# Nitin Punjabi
# nptoronto@yahoo.com
# https://github.com/nitinpunjabi
def merge(left, right):
a_list = []
left_len = len(left) if left else 0
right_len = len(right) if right else 0
left_idx = 0
right_idx = 0
while left_idx < left_len and right_idx < right_... |
# Solution to Exercise 4.1 from Cracking the Coding Interview, 5th Edition
# Nitin Punjabi
# nptoronto@yahoo.com
# https://github.com/nitinpunjabi
def height(node):
if not node:
return False
return 1 + max(height(node.left_child), height(node.right_child))
def is_balanced(node):
if not node:
... |
# Solution to Exercise 2.6 from Cracking the Coding Interview, 5th Edition
# Nitin Punjabi
# nptoronto@yahoo.com
# https://github.com/nitinpunjabi
import linked_list as lst
def detect_loop_with_floyds(lst):
slow_runner = lst.head.next
fast_runner = lst.head.next.next
while slow_runner is not fast_... |
# Implementation of a directed graph.
class Vertex:
def __init__(self, key):
self.key = key
self.colour = 'white'
self.connected_to = {}
def add_neighbour(self, vert, weight=0):
self.connected_to[vert] = weight
def get_connections(self):
return self.connected_to.keys()
de... |
# Solution to Exercise 11.7 from Cracking the Coding Interview, 5th Edition
# Nitin Punjabi
# nptoronto@yahoo.com
# https://github.com/nitinpunjabi.
def partition(elems, attr, left, right):
first = left
piv = elems[first][attr]
piv_pair = elems[first]
while left <= right:
while left <= right ... |
# Solution to Exercise 4.5 from Cracking the Coding Interview, 5th Edition
# Nitin Punjabi
# nptoronto@yahoo.com
# https://github.com/nitinpunjabi
import binary_search_tree as bin
import sys
def _is_bst(node, min_val, max_val):
if node is None:
return True
if node.item > min_val and\
node.i... |
#
# CS106 Final Project
# CryptWing
#
# classical ciphers
#
# Shion Fukuzawa (sf27)
# December 15, 2016
#
# This file includes the implementations of the Transposition, Caesar, Viginere, and Playfair ciphers.
#
# Algorithms referenced from
# http://practicalcryptography.com/
#
from cipher import Cipher
class Tran... |
n = int(input())
vote=input()
if vote.count('A')>vote.count('B'):
print('A')
elif vote.count('A')<vote.count('B'):
print('B')
else:
print('Tie')
|
n=int(input())
a=list(input() for _ in range(n))
def lcm(a, b):
return a-b
for i in range(n):
b=a[i].split( )
b[0]=int(b[0])
b[1]=int(b[1])
b[2]=int(b[2])
if b[0]<lcm(b[1], b[2]): print("advertise")
elif b[0]==lcm(b[1], b[2]): print("does not matter")
else: print("do not advertise")
|
import random
# Helper functions ----------------------------------------------------------------------------------------------------------------------------------
def make_node_barrier(node):
"""Turns a node into a hard barrier."""
node.make_barrier()
node.is_hard_barrier = True
return node
def no... |
'''
glas = "aeoui"
countG = 0
sogl = "sdfghjkl"
countS = 0
str_1 = "Privet, mir ya zdes"
'''
print("hgehgrorehre")
print("hgehgrorehre")
print("hgehgrorehre")
print("hgehgrorehre")
print("hgehgrorehre")
print("hgehgrorehre")
print("hgehgrorehre")
print("hgehgrorehre")
print("""hgehgrorehreerpgkr
e
ger
gkpregkpr[egk
... |
# vim: set fileencoding=utf-8 :
def textextract(data, startstr, endstr, startpos = 0):
''' extracts a text from data, which is between startstr and endstr
if startstr is '' it will extract from the beginning of data
if endstr is '' it will extract until the end of data
the optional parame... |
import random as rand
import string
symbols = string.punctuation
lowerLetters = string.ascii_lowercase
upperLetters = string.ascii_uppercase
letters = lowerLetters + upperLetters
nums = string.digits
passwordList = []
while True:
try:
passLength = int(input("How long do you want you password (8 as a minim... |
def partition1(arr,low,high):
i = ( low-1 ) # index of smaller element
pivot = arr[high] # pivot
for j in range(low , high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
... |
class Node(object):
"""docstring for Node"""
def __init__(self, x):
self.val = x
self.leftpre = None
self.rightnext = None
class Solution(object):
"""docstring for Solution"""
def mergeCDL(self, a, b):
if not a: return b
if not b: return a
aEnd = a.leftpre
bEnd = b.leftpre
a.leftpre = bEnd
bEnd.... |
from Student import Student
from Assessment import Assessment
from Histogram import Histogram
#This function reads the information of classlist.txt
#It can filter an error if the file is correct
#And returns in order of ID, name, e-mail and empty list for marks
def read_classlist(filename):
try:
student... |
class Card:
def __init__(self, values, colors):
v = ''
value = None
if values == 1:
v = 'Ace of '
value = [1, 11]
elif values == 11:
v = 'Jack of '
value = 10
elif values == 12:
v = 'Queen of '
value = 10
elif values == 13:
v = 'King of '
value =... |
punctuation = '''''!()-[]{};:'"\,<>./?@#$%^&*_~'''
str = input("Enter a string: ")
no_p = ""
for char in str:
if char not in punctuation:
no_p = no_p + char
print(no_p)
|
#! venv/bin/python
#_*_ encoding:utf-8 _*_
"""
@Python -V: 3.X
@SoftWave: Pycharm
@OS: Ubuntu
@Author: SKYNE
@Contact: 520@skyne.cn
@Time: 20184.
"""
def shellSort(alist):
sublistconut = len(alist) // 2
while sublistconut > 0:
for startposition in range(sublistconut):
gapInsertionSort(alis... |
# x, y 데이터 세트가 있을 때, 이차 방정식 y = w1x^2 + w2x + b를 만족하는
# parameter w1, w2, b를 추정한다.
# -------------------------------------------------------------------
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# y = 2x^2 + 3x + 5 일 때 dataX, dataY 집합을 생성한다
dataX = list(np.arange(-5, 5, 0.5))
dataY = [... |
"""
Download Youtube video and convert them into mp3 and delete the dowloaded video
2019
Author:
Jeremy Lefort-Besnard jlefortbesnard (at) tuta (dot) io
"""
# Library we need
from pytube import YouTube
import os
import time
import moviepy.editor as mp
import glob
from sys import platform
impo... |
#packing은 tuple만 가능
t = 10, 20, 30, 'python'
print(t, type(t))
#unpacking
a,b,c,d = t
print(a,b,c,d)
#packing & unpacking
a,b,c,d = 10, 20, 30, 'haha'
print(a,b,c,d)
#unpacking error
#a,b,c = (10,20,30,40)
#unpacking extended
a, *b = (1,2,3,4)
print(a)
print(b)
*a, b = (1,2,3,4,5)
print(a)
print(b)
a, *b, c = (1,... |
import socket
def sendmsg(sock, msg):
""" A technique to send messages of varying length."""
message = msg
if not type(msg) == bytes:
message = msg.encode('ascii')
length = len(message)
if length > 9999:
raise OverflowError('Message is too large.')
length = "%.4d" % le... |
class Nodo:
def ___ini___(self);
self.nombre = None #None es nulo
self.apellidos = None
self.next = None
"""
self.apellido es como delcarar
char *nombre;
la funcion init es la que crea los nodos
"""
def eliminar(self):
self= None
class Lista:
def __in... |
# -*- coding: utf-8 -*-
"""
定义状态类State
"""
class State:
def __init__(self, monkey=-1, box=0, banana=1, if_on_box=-1):
# 默认的初始状态是猴子在A处,箱子在B处,香蕉在C处,猴子没有站在箱子上
# -1:猴子在A处,0:猴子在B处,1:猴子在C处
if monkey is "A":
self.monkey = -1
elif monkey is "B":
self.monkey = 0
... |
import copy, re
def integerEncode(num):
'''switch integer to encode list'''
numBinary = bin(num)[2:] # first we convert integer to binary
resultEncode = [] # store result
singleEncodeNum = '' # string ty... |
"""
If the numbers 1 to 5 are written out in words:
one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
"""
specialDigit = [3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8... |
#Generates all primes up to a number n using an initial list
import sys
sys.path.insert(0, '/Users/brianroper/Dropbox/03 - Code/roper_library')
sys.path.insert(0, 'C:\Users\Brian/Dropbox/03 - Code/roper_library')
import math
from fileToIntList import fileToIntList
from listToFile import listToFile
from os.path import... |
"""
2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2**1000?
"""
number = 2**1000
number = str(number)
totalSum = 0
for i in range(len(number)):
totalSum += int(number[i])
print(totalSum)
|
#强迫症老板和他的洗碗工
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size... |
#最近的请求次数
def func(mylist):
# your code here
temp = mylist
var1 = 0
for i in range(len(mylist)-1):
temp[i] = mylist[i] - 10000
output = temp
return output
mylist = eval(input())
print(func(mylist))
|
import numpy as np
import scr.StatisticalClasses as Stat
class Game(object):
def __init__(self, id, prob_head):
self._id = id
self._rnd = np.random
self._rnd.seed(id)
self._probHead = prob_head # probability of flipping a head
self._countWins = 0 ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 21:43:14 2018
@author: Chris Dryden
"""
import re
f = open('words.txt', 'r')
longest = 0
longestword = ' '
for word in f:
if re.match("^[ABCDEF]*$", word):
length = len(word)
if length > longest:
longest = length
longestwor... |
from flask import Flask, render_template, request
import requests
import json
app = Flask(__name__)
## Challenge 1
# If you go to http://localhost:5000/square, it would a display a form
# Update the view function that receives the data from the form and returns square of the number
@app.route('/square')
def squareVie... |
一、数学运算:
1、合数组
a=array([[ 1, 2],
[ 3, 4]])
b=array([[ 2, 2],
[ 2, 2]])
c=np.vstack((a,b)) #垂直
d=np.hstack((a,b)) #水平
2、
e=a.tolist() #数组转列表
f=np.array(e) #列表转数据
3、
a = np.zeros((437647,18))
a[:,1]=dataset.values[:,1] #把 dataset第一列值 赋值给 数组a的第一列
4、
list(map(lambda x: int(x),years)) #字符串型列表 转 整型列表... |
#读单个文件
def returndata2(filename):
data1,data2,data3,data4=[],[],[],[] #可以添加识别几个参数
with open(filename,'r') as f:
lines=f.readlines()
for line in lines:
value=[s for s in line.split( )]
data1.append(str(value[0])) #根据数据类型确定 str float。
data2.append(str(value[1]))
data3.append(float(value[20]))
data4... |
# Multiple Operations on a Computational Graph
# In this script, we will create an array and perform two multiplications on it,
# followed by addition:output = (input) * (m1) * (m2) + (a1)
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
import os... |
import math
def antWalking(n):
n, d = pow(math.factorial(n) / pow(math.factorial(n / 2), 2), 2), pow(4, n)
m = gcd(d, n)
if (m != 0):
return [n / m, d / m]
else:
return [n, d]
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b, a % b)
print antWalkin... |
ff = raw_input("Enter a file name: ")
f = open(ff)
flst = f.readlines()
count = 0
info = ""
# records information in string form about files without . extensions at the end
while count < len(flst):
tmp = flst[count].split()
if tmp[0] >= 30 and tmp[3].count(".") == 0:
info += "".join(flst[... |
def main():
print "enter values to be analyzed, use -1 to end list"
data = []
num = input("enter your number: ")
while num != -1:
data.append(num)
num = input("enter your number: ")
avg = average(data)
print 'average of data values is ', avg
def average(data):
... |
#Program For BOOK Mangment System
String_1 = "1: For Add Books\t\t\t\t"
String_2 = "2: For Edit Books (Note: You Must Add Some Record In Order to Search Edit Or View Records)\n"
String_3 = "3: For View Books Record\t\t\t\t4: For Search Books\t\t\t\t5:Exit"
X = 1
B = 1
A = 1
print("{}{}{}".fo... |
team_name = 'one of one' # the new team name is defined as a string
strategy_name = 'Judas' # the name of the strategy is defined as a string
strategy_description = 'If the opponent betrays in either the most recent or two most recent moves, the decision to betray is made. Otherwise, the function decides to collude.'
... |
from stack import *
class WordProcessor:
def __init__(self):
self._stack = Stack()
self._undo = Stack()
self._redo = Stack()
self.last_call = ''
def undo(self):
"""
Reverses the last action that was made to main _stack if it is valid.
"""
try:
... |
# __auther__:pangdahai
# __date__:2017/10/26 22:30:15
import copy
# Python 2.x ASSIC (#!-*- coding:UTF-8 -*-)/(#coding:utf-8)
# Python 3.x unicode
# unicode 兼容GBK,GB
# UTF-8 unicode的扩展
# 单行注释
'''多行注释'''
"""多行注释"""
# 用户输入,所有输入数据都是字符串
# inVal = input("input value:")
name = "pangdahai"
age = 22
job = "student"
salary... |
import itertools
"""返回迭代器对象"""
# 累加
x = itertools.accumulate(range(10))
print(list(x))
# 连接多个列表或迭代器
x = itertools.chain(range(3), range(4), [3, 2, 1])
print(list(x))
# 求列表或生成器中指定数目的元素不重复的所有组合
x = itertools.combinations(range(4), 3)
print(list(x))
# 允许重复元素的组合
x = itertools.combinations_with_replacement('ABC', 2)
pr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
miLista = [];
print "Vamos a introducir 4 elementos a una lista.\n";
miLista.append(raw_input('Introduce elemento 1: '));
miLista.append(raw_input('Introduce elemento 2: '));
miLista.append(raw_input('Introduce elemento 3: '));
miLista.append(raw_input('Introduce elemento 4: '... |
from typing import List
from itertools import accumulate
import math
def skew(samples: List[float], mu: float, sigma: float):
"""Unfortunately this is implemented in third_party/differential-privacy/cc/algorithms/distributions_test.cc
and we don't want to pull the test files in. I'm assuming it'll be moved... |
import sys
import os
import shutil
# 把资源文件夹里的资源按照是否相等复制一份到输出目录
def copyFiles(resourcePath: str, dirName: str, outputPath: str):
fileList = []
totalFiles = 0
for root, dirs, files in os.walk(resourcePath):
for file in files:
filePath = os.path.join(root, file)
targetPath = ... |
import tensorflow as tf
# Steps:
# 1. Initialize the variables W, x, b
# 2. Create a loss function for linear regression
# 3. Train a gradient descent optimizer
# 4. Evaluate the accuracy
# Step 1: Initialize the variables
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeho... |
class student:
school = 'ecorvi'
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
def avg(self):
return(self.m1+self.m2+self.m3)/3
def get_m1(self):
return self.m1
def set_m1(self):
self.m1=33
@classmethod
... |
from numpy import *
arr =array([[1,2,3,7,8,9],[4,5,6,1,2,3]])
print(arr)
print(arr.dtype) # int 32 ...type of data
print(arr.ndim) # dimensional -2d
print(arr.shape) # (2,6)
print(arr.size) # 12
arr1=arr.flatten()
print(arr1) # [1,2,3,7,8,9,4, 5,6,1,2,3]
arr2= arr... |
pos=-1
def search(list,n):
i=0
while i< len(list):
if list[i] == n:
globals() ['pos'] = i
return True
i=i+1
return False
list = [4,5,7,8,6,4,3]
n=4
if search(list,n):
print('found at ',pos+1)
else:
print('not found')
|
# Open these files that were created
medFile = open("antideprecords.txt", "r")
npizip = open("npiandZip.txt", "r")
# Open this new file, with write permissions
antidepPerZip = open("numAntidepPerZip.txt", "w")
# Create the dictionaries
dictNpiZip = {}
tallyZip = {}
# Go through npizip.txt and create a dictionary: k... |
import math
def run():
print('CALCULO DE VOLUMENES'.center(74, '*'))
msg1 = """
→ Elige el tipo de cuerpo al que quieres calcular el volumen:
1. Cubo
2. Cilindro
3. Esfera
4. Cono
5. Salir
"""
print(msg1)
respuesta = int(input("Cual es tu... |
"""
Generate prime numbers from 0 to n with asymtotic analysis
An assumption with this analysis is that each time their is an iteration, a constant time taken is presumed
Say there will be 20 iterations, 20 units of time will be executed
Worst case scenario for nested loops is O(N^2) meaning the performance of this a... |
###注释
##这是一个计算圆的面积的程序
#冲冲冲
r=12
area=3.14159265*r**2
print('面积是',area)
print('No!')
print('Hello') |
import cs50
def main():
height = getheight()
printpyramid(height)
def getheight():
height = int(input("Height of pyramid: "))
while height > 23 or height < 0:
height = getheight()
return height
def printpyramid(h):
for i in range(1,h+1):
{
#note the reduction of th... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 softtabstop=4 shiftwidth=4
"""
Given a binary search tree, design an algorithm which creates a linked list of all the
nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).
Analyse:
* I don't know why it's must a BST.
""... |
#Question: Write a program to calculate x^n
#Answer:
#1. Observation:
# 1.1 exponent is a positive integer
#2. Algorithm:
# 2.1: Dividing & conquering using the least significant bit in the exponent and using a iterative function will improve efficiency
#3. Complexity
# 3.1: O(n/2) where n is the expon... |
'''
Question:Given a source word, target word and dictionary, transform the source word to target
by changing/adding/removing 1 character at a time, while all intermediate words being valid
words in the dictionary. Return the transformation chain which has the smallest number of intermediate words.
#Modified from htt... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
Write a method to generate a random number between 1 and 7, given a
method that generates a random number between 1 and 5 (i.e., implement
rand7() using rand5())
"""
import random
def rand5():
return random.randint(1,... |
#Binary Search Tree Library
class BSTNode:
def __init__(root, data):
root.left = None
root.right = None
root.data = data
def insertNode(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.left == None:
root.l... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
Imagine you have a call center with three levels of employees: fresher, technical lead (TL), product manager (PM). There can be multiple employees, but only one TL or PM. An incoming telephone call must be allocated to a fre... |
import donnees
import random
def recup_name():
name=input('enter name ')
return name
def initialize_data():
authorized_words=donnees.liste_mots
number_max=donnees.nb_chances
return (authorized_words,number_max)
def choice_of_word(authorized_words):
i=0
word=list(authorized_words[int(len(a... |
# -*- coding: utf-8 -*-
import math
# 生成分布的页码
def paginate(page, per_page, total):
pagination = {'page':page}
tmp_pages = range(1, int(math.ceil(total/float(per_page)))+1)
idx = tmp_pages.index(page)
if len(tmp_pages) <= 10:
pagination['pages'] = tmp_pages
else:
if idx - 5 >= 0:
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def permutation_enumerator(items, n=None):
'''
generate all permutation of given items.
'''
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
... |
#Tony K.
#Theory ASCII & Unicode Task 1
#30/09/2014
print("This programm converts between Text and ASCII")
user_input = input("Do you want to convert ASCII or Text: ")
if user_input == ASCII:
user_input_ascii = input("Please enter the ascii number you want to transfer: ")
elif user_input == Text:... |
# https://fellowship.hackbrightacademy.com/materials/challenges/is-palindrome/index.html
"""Is this word a palindrome?
>>> is_palindrome("a")
True
>>> is_palindrome("noon")
True
>>> is_palindrome("racecar")
True
>>> is_palindrome("porcupine")
False
Treat spaces and uppercase letter... |
print ("Calculando");
num = 4
factorial = 1
if num < 0:
print("Error")
elif num == 0:
print("El factorial de 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("El factorial de",num,"es",factorial) |
#Inicia Lista Comum
lista = [1,2,3,4,5]
#Copia elemento por elemento para a nova lista
lista2 = [x for x in lista]
#Copia todos os elementos que forem pares
lista_pares = [x for x in lista if x%2==0]
#Copia elementos ao quadrado da lista
lista_quadrado = [x**2 for x in lista]
print(lista)
print(lista2)
print(lista... |
# %%
"""
# Using Probability Distributions as Parameters
In most cases, augmentation that employs simple uniform distributions is enough to produce good results. E.g. in the case of rotation via affine transormations, one could provide a uniform distribution `(-30, 30)`, which would lead to images being rotated by a r... |
# # create an empty list
# stuff = list()
# # add items to the list.
# stuff.append('book')
# # stuff.append(99)
# # print(stuff)
# stuff.append('cookie')
# stuff.append('equal')
# stuff.append('apple')
# # print(stuff)
# # sort the list in alphabetical order
# stuff.sort()
# # print the list.
# print(stuff)
# the fol... |
"""
Problem statement:
Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target.
Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target.
Example 1:
Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
E... |
"""
Problem statement:
Problem 1: Given an unsorted array of numbers and a target ‘key’, remove all instances of ‘key’ in-place and return the new length of the array.
Example 1:
Input: [3, 2, 3, 6, 3, 10, 9, 3], Key=3
Output: 4
Explanation: The first four elements after removing every 'Key' will be [2, 6, 10, 9].
E... |
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
""" Tests for name_funnction.py """
def test_first_last_name(self):
""" Test the results when first and last name is passed """
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted... |
# Getting input from user
# print("Hello World!")
"""
name = input("What's your name: \t")
print(name)
"""
# Testing set, dict, list properties
"""
obj = set({'name': 'Akshay', 'age' : 25, 'gender': 'male'});
print("Checking value in set: ", 'Akshay' in obj)
"""
# Polling set
"""
polling_data = {}
#print(len(... |
"""
Problem statement:
iven an array, find the length of the smallest subarray in it which when sorted will sort the whole array.
Example 1:
Input: [1, 2, 5, 3, 7, 10, 9, 12]
Output: 5
Explanation: We need to sort only the subarray [5, 3, 7, 10, 9] to make the whole array sorted
Example 2:
Input: [1, 3, 2, 0, -1, 7... |
class shapes:
def square(self,s):
self.side=s
def rectangle(self,l,b):
self.length=l
self.breadth=b
def calculate(self):
self.periofasquare=4*s
self.periofarect=2*l+2*b
self.areaofasquare=s*s
self.areaofarect=l*b
def display(self):... |
#Given an input string, print the string with the first and last letter removed if they were equal, or the original string if they were not.
inputStr = 'test'
if inputStr[0]==inputStr[-1]:
print(inputStr[1:3])
else:
print(inputStr)
|
import matplotlib.pyplot as plt
func = lambda t, y: y - t**2 + 1
def getIntervals(a, b, h):
while a <= b:
intervals.append(a)
a += h
y0 = 0.5
N = 10
a = 0.0
b = 2.0
h = (b-a)/N
intervals = []
weights = []
weights.append(y0)
getIntervals(a, b, h)
def rungeKutta(func, w, t, h):
k1 = h * func(t,w)
k2 = h * func... |
name = input("Please Enter Your Name : ")
print("Hello {0}.".format(name))
age = int(input("How Old Are You? : "))
if 21 < age < 31:
print("welcome to the party")
else :
print ("Sorry you do not meet the given guidelines of age")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.