text stringlengths 37 1.41M |
|---|
from os import getpid
def length(word):
'returns length of string word'
print('Process {} handling {}'.format(getpid(), word))
return len(word)
animals = ['hawk', 'hen', 'hog', 'hyena']
print([length(x) for x in animals])
|
from matrix import Matrix
import time
def main():
matrix1 = Matrix(2, 3)
matrix1.add_elements()
matrix1.show_elements()
print("\n")
matrix2 = Matrix(3, 2)
matrix2.add_elements()
matrix2.show_elements()
print("\n")
matrix3 = matrix1.addsub(matrix2)
try:
matrix3.show_elements()
print("\n")
except ... |
from Pathfinding.Maze.maze import Maze
class DFS():
def __init__(self):
self.maze = Maze()
self.state = "S"
self.open_list = [self.state]
self.close_list = []
def search(self):
while self.open_list is not None:
print("Open list", self.open_list)
... |
def coloredBoard(col, size, a, b):
board = [0,]*size
columns = [0,]*size
for x in range(len(board)):
board[x] = columns
for row in range(len(board)):
for co in range(len(board[row])):
board[row][co] = (a*row + b*co) % col
print(board[row][co], end="")
... |
import math
class Circle:
def __init__(self, r):
self.radius = r
def area(self):
return math.pi * self.radius ** 2
|
#without print line convert to integer
num = int(input("please enter please enter a number - "))
|
#with print line convert to integer
print("please enter please enter a number - ")
num = int(input())
|
# this is a little program for simple calculator
#functionalities are Addition. subtraction, division and Multiplication
from math import *
import time
def cal():
a = int (input("Enter your first number: "))
b = int (input("Enter your second number: "))
c = input("What you want to do: ")
... |
import unittest
from pascals_triangle import triangle, row, is_triangle
class PascalsTriangleTest(unittest.TestCase):
def test_triangle1(self):
ans = ['1', '1 1', '1 2 1', '1 3 3 1', '1 4 6 4 1']
self.assertEqual(triangle(4), ans)
def test_triangle2(self):
ans = ['1', '1 1', '1 2 1',... |
def apple_price(apple_num):
box = 0
if apple_num % 5 == 0:
box = apple_num//5
else:
box = apple_num//5+1
print("苹果的总价格是:",apple_num*2+box)
return apple_num*2+box
def pineapple_price(pineapple_num):
print("菠萝的总价为:",pineapple_num*8+pineapple_num)
return pineapple_num*8+pineap... |
# import the method from project folder
from .map import inc
from .map import searchbar
from .map import dist
from .map import borough
from .map import Biz
# this is a sample test from prof paine's project
def test_inc():
""" Tests the increment function
Parameters
----------
none
"""
assert... |
#SD
#Given a string in all caps, this program shifts the characters to left by 4, i.e A becomes E and Z becomes D
#!/usr/bin/python
import sys
import string
def cypher_string(string):
cypher_string = ''
for c in string:
if ord(c) < 65 or ord(c) > 90:
cypher_string += c
elif ord(c) >= 87 :
x... |
import random
import time
class Tuile:
def __init__(self, nom, couleurTop, couleurBot, couleurLeft, couleurRight):
"""nouvelle_tuile (Tuile, str, str, str, str, str) -> Tuile"""
self.nom = nom
self.couleurTop = couleurTop
self.couleurBot = couleurBot
self.couleurLeft = coul... |
def print_gugudan(n):
if type(n)!=int:
return
elif n<1 or n>9:
return
else:
for x in range(1,10):
print(n,'×',x,'=',n*x)
print()
print_gugudan(4)
print_gugudan(9)
print_gugudan(13)
print_gugudan('안녕') |
import os
import csv
file_path = os.path.join("Resources", "budget_data.csv")
def average(numbers):
average = sum(numbers)/len(numbers)
return average
def to_currency(value):
return '${:,}'.format(value)
with open(file_path, 'r') as csvfile:
budget_data_reader = csv.reader(csvfile, delimiter=',')
... |
# The block below is due to pycraft on StackOverflow:
# https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
# Following code is adapted from his answer
###
from os import listdir, getcwd
from os.path import isfile, join
###
cwd = getcwd()
onlyfiles = [f for f in listdir(cwd+"/figure_inte... |
num = int(input("How many numbers? "))
total = 0
for n in range(num):
marks = float(input("Enter number: "))
total += marks
print(f"Total marks is: {total}")
avg = total/num
print(f"The avarege is : {avg}")
|
fruits=[]
for i in range(7):
f = input("Enter fruits name: ")
fruits.append(f)
print(fruits)
|
# c1, u1, p1 = input().split(" ")
# c2, u2, p2 = input().split(" ")
#
# total = (int(u1) * float(p1)) + (int(u2) * float(p2))
#
# print("VALOR A PAGAR = R$ %.2f" %total)
#
c1, u1, p1 = input().split(" ")
c2, u2, p2 = input().split(" ")
product1 = int(u1) * float(p1)
product2 = int(u2) * float(p2)
total = float(product... |
class_qty = int(input("How many classes are you taking this semester? "))
total = []
for classes in range(class_qty):
className = input("Enter the name of the class: ")
total.append(className)
# https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/
print("The classes you are taking are: ", *tot... |
"""
# -------------------------------------------------------------------------------
# network.py
# -------------------------------------------------------------------------------
#
# load stations, load connections and print csv
#
# Team de Brein Trein
#
"""
import csv
from .station import Station
class Network()... |
#Taking number from user and check it is even or odd
enterNumber = int(input("Enter a value: "))
modeValue = enterNumber % 2
if modeValue == 0:
print(enterNumber,"is an even value")
else:
print(enterNumber,"is a odd value")
#Taking the range of number from the user to find even and odd using for loop
# taki... |
#!/usr/bin/env python3
nameList = []
numberList=[]
# for i in range (3):
'''
while True:
enterName = str(input("Enter name: "))
enterNumber = int(input("Enter number: "))
nameList.append(enterName)
numberList.append(enterNumber)
print('Do you want to insert another user...')
want_to_insert = in... |
"""
examples of how to search for events using different search criteria
"""
from eventregistry import *
import json
er = EventRegistry()
# get the concept URI that matches label "Barack Obama"
obamaUri = er.getConceptUri("Obama")
print("Concept uri for 'Obama' is " + obamaUri)
#
# USE OF ITERATOR
# example of usin... |
#!/usr/bin/python3
"""Unittest for Amenity
"""
import unittest
from models.base_model import BaseModel
from models.amenity import Amenity
from datetime import datetime
class TestAmenity(unittest.TestCase):
"""Test for Amenity"""
@classmethod
def setUpClass(self):
"""Instances for testing on"""
... |
a = input("Write a number: ")
b = input("Write another number: ")
c = a+b
print(c)
c="13"
d=input("type 37 and press [enter]:")
e=37
cc=int(c)
dd=int(d)
print(c+d)
print(cc+dd)
print(cc+e)
print(c+e)
print(type(c))
print(type(d))
print(type(e))
print(type(cc))
# A simple calculator made as an introduction to pro... |
print("Please input a tuple, (M, p). The output is the probability that for a random index, n < M, the nth member of the Van Eck sequence is zero or within p percent of n.")
tuple = input()
M, p = map(int, tuple[1: len(tuple) - 1].split(", "))
#STEP 1: Fill an array called dontknow with the first M entries of the Van... |
""" Hackathon - Level 3 """
def oddish_evenish_num(n):
"""
Returns Oddish if odd, else returns Evenish
Parameters
----------
n : integer to evaluate
Returns
-------
Oddish: if n == odd
Evenish: if n == even
"""
return 'Oddish' if sum(map(int, str(n))) % 2 else 'Eveni... |
"""Finding a second smallest number"""
li1 = []
len = int(input("enter the length of list:"))
for i in range(0,len):
ele = int(input("enter element:"))
li1.append(ele)
print(li1)
li1.sort()
print("second smallest",li1[1])
|
""""Append a list to second list"""
li1 = []
li2 = []
def ele_list(l):
n = int(input("enter the length of list:"))
for i in range(0,n):
ele = int(input("enter the element:"))
l.append(ele)
return l
print("elements in list 1:",ele_list(li1))
print("elements in list 2:",ele_list(... |
"""largest no in list"""
li1 = []
len = int(input("enter the length of list:"))
for i in range(0,len):
ele = int(input("enter element:"))
li1.append(ele)
print("maximum no in list",max(li1)) |
################
#### Person ####
################
class Person(object):
"""Person class.
>>> steven = Person("Steven")
>>> steven.say("Hello")
'Hello'
>>> steven.repeat()
'Hello'
>>> steven.greet()
'Hello, my name is Steven'
>>> steven.repeat()
'Hello, my name is Steven'
... |
## Review on Dictionary
def merge_dict(d1, d2):
"""Returns a dictionary with two dictionaries merged together. You can assume that the same keys appear in both dictionaries.
>>> data8 = {"midterms":1, "projects":3}
>>> data100 = {"midterms":2, "projects":3}
>>> combined = merge_dict(data8, data100)
... |
# Lambda
def compose(f, g):
"""Write a function that takes in 2 single-argument functions, f and g, and returns another lambda function
that takes in a single argument x. The returned function should return the output of applying f(g(x)).
Hint: The staff solution is only 1 line!
Return the compositio... |
# Question 1
def converter(temperatures, convert):
"""Returns a sequence that converts each Celsius temperature to Fahrenheit
>>> def convert(x):
... return 9.0*x/5.0 + 32
>>> temperatures = [10, 20, 30, 40, 50]
>>> converter(temperatures, convert)
[50.0, 68.0, 86.0, 104.0, 122.0]
"""
... |
# 空间复杂度o(1)
# 时间复杂度o(n^2):1+2+3+...(n-1)=n*(n-1)/2
def insert_sort(alist):
if alist == [] or alist is None:
return
for i in range(1, len(alist)):
x = alist[i]
j = i
while j > 0 and alist[j-1] > x: # [4], 1, 9, 3, 11, 5, -1]从后面到前面依次比较
alist[j] = alist[j-1]
... |
# -*- coding:utf-8 -*-
# Sort Array By Parity
# 题目大意:
# 给出一个非负整数的数组A,返回一个由A的所有偶数元素组成的数组,后跟A的所有奇数元素
# 例如:Input: [3,1,2,4]
# Output: [2,4,3,1]
# The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
#
# 题目解析:
# 一般都是要先判断数组中的元素为奇偶数,然后进行排序,如方法1,
# 要么就是使用首尾指针指向的元素进行判断奇偶性,再交换位置进行排序,如方法2
# 再者,使用pyt... |
list=[]
k= int(input())
for i in range(0,k):
str=input("")
str1=str.split()
if str1[0]=="insert":
list.insert(int(str1[1]),int(str1[2]))
elif str1[0]=="print":
print(list)
elif str1[0]=="remove":
list.remove(int(str1[1]))
elif str1[0]=="append":
list.append(int(st... |
"""
Write a Python program to split a given dictionary of lists into list of dictionaries.
Input :
{'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}
, {'Science': 89, 'Language': 78},
{'Science': 62, 'Language': 84}, {'Science': 95, 'Language': 80}
]
Output :
[
{'Science': 88, 'Language': 77},{'Science': 89, ... |
"""# 7
یک عدد n به عنوان ورودی دریافت میکنیم.
بین هر دو عددی در بازه 1 تا n ب.م.م یا همون GCD میگیریم.
بزرگترین ب.م.م بین همه ب.م.م های به دست اومده چه عددی هستش؟
Input : 3
Output: 1
GCD(1,2)=1
GCD(1,3)=1
GCD(2,3)=1
Input: 5
Output:2
"""
#import math
import numpy as np
n = int(input('N is: '))
x = range(1, n + 1)
sq=s... |
import numpy as np
import pandas as pd # I want to read the txt file as dataframe
def get_p_b_cd():
# you need to implement this method.
p_b_cd = np.zeros((3, 3, 2), dtype=np.float)
for c in range(1, 4):
for d in range(1, 3):
for b in range(1, 4):
sum_total = su... |
# File: q3.py
# Author: Brittany Vamvakias
# Date: 02/11/2020
# Section: 501
# E-mail: brittvam@tamu.edu
# Description: This code takes an input from the user and checks whether or not it contains two identicle consecutive letters and prints whether it does or not. This code continues to run until the user types "quit"... |
from pprint import pprint
import sys
books = []
print("*********Please see below choices***********")
user_choice = """Enter:
- 'a' to add a new book,
- 'd' to delete a book,
- 'l' to list all books,
- 'r' to mark a book as read
- 'q' t... |
'''
8 - Write a function that will play a rubbish version of the board game snakes and ladders
(https://en.wikipedia.org/wiki/Snakes_and_Ladders).
In this game, two players compete to get from square 1 to square 100.
Players take alternative turns, and move between 1 and 6 spaces based on a random
roll of the dice... |
"""
10 - Create a function that takes time in the 24-hour clock (e.g. “23:30”) and
converts to the 12-
hour clock (e.g. “11:30 PM”). Print the result to screen.
"""
from random import randint
def hour_convert(h,m):
if h > 12:
print(f"{h-12}:{m} P.M.")
elif h == 12:
print(f"12:{m} P.... |
from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self, side):
super().__init__()
self.score = 0
self.side = side
self.penup()
self.hideturtle()
self.color("white")
if self.side == "p1":
self.goto(-30, 360)
if self.side == "... |
from note_content import NoteContent
from collections import deque
class NoteGroup(object):
"""
This class deals with handling groups of notes and provides
useful methods for generating data for the reports. Changes
will be made as needed to reflect new features.
"""
def __init__(self, *notes... |
import RPi.GPIO as GPIO
import argparse
import json
import time
# Refer to the pin numbers by their pin number since BCM codes change between Pi versions.
# See https://raspberrypi.stackexchange.com/questions/12966/what-is-the-difference-between-board-and-bcm-for-gpio-pin-numbering
GPIO.setmode(GPIO.BCM)
# rc_time ge... |
k=int(input("enter the number:"))
sum=0
while(k>0):
sum=sum+k%10
k=k//10
print("sum of the digits=",sum)
|
MaxCapacity = 13
import time
class Elevator:
"""constructor"""
def __init__(self, id, maxFloor, floor=1):
self.floor = floor
self.id = id
self.people = []
self.doortime = 0.15
self.traveltime = 0.03
self.direction = 'idle' # or 'up' or 'down'
self.list... |
import sys
class Heap():
def __init__(self, size):
self.heap = [-1]*size
self.HEAP_SIZE = 0
def heapify(self, index):
"""
Top down approach
To check Min heap property
"""
left = 2*index + 1
right = 2*index + 2
min_ind = index
i... |
'''
A multiple-source BFS works in exactly the same way as regular BFS,
but instead of starting with a single node, you would put all your sources (A's)
in the queue at the beginning. That is, make a pass over the grid to find all A's
and initialize your BFS queue with all of them at distance 0. Then proceed with BFS a... |
'''
Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
A move is guaranteed to be valid and is placed on an empty block.
Once a winning condition is reached, no more moves is allowed.
A player who succeeds in placing n of their marks in a horizontal, vert... |
'''
604. Design Compressed String Iterator
Design and implement a data structure for a compressed string iterator.
It should support the following operations: next and hasNext.
The given compressed string will be in the form of each letter followed by a positive
integer representing the number of this letter existi... |
from collections import defaultdict
import itertools
def get_signature(word):
x = [0]*26
for w in list(word):
x[ord(w) - 97] += 1
return x
def get_index(m, n):
for i in range(len(m)):
if abs(m[i] - n[i]) > 0:
return chr(97+i)
def get_index_(a, b):
mp_a = defaultdict(la... |
'''
159. Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”,
T is "ece" which its length is 3
'''
def main():
word = input()
character_dict = {}
index_array = [-1]*le... |
'''
* Google
* Given a list of non-negative numbers and a target integer k,
* write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.
'''
def validate(arr, k):
for i in range(1, len(arr)):
... |
from collections import defaultdict
from queue import PriorityQueue
import sys
def initialize_graph():
V, E = [int(x) for x in input().split()]
graph = defaultdict(list)
for i in range(E):
a, b = [int(x) for x in input().split()]
graph[a].append([b, 0])
graph[b].append([a, 0])
... |
def check_palindrome(word):
start, end = 0, len(word)-1
while start < end:
if word[start] == word[end]:
start += 1
end -= 1
else:
return False
return True
def check_possible(x, y):
n = len(x)
for first_cut in range(n):
for second_cut in ... |
array2d = []
for i in range(3):
new_line = []
for j in range(3):
new_line.append("-")
array2d.append(new_line)
def show():
for i in array2d:
for j in i:
print(j, end=' ')
print()
def win():
for i in range(3):
if array2d[0][i] == array2d[1][i] == array2... |
import sympy
import numpy
import random
import time
import matplotlib.pyplot
class cryptography_algorithm(object):
def __init__(self,plaintext,cybertext):
self.plaintext = plaintext
self.cybertext = cybertext
def encryption(self):
pln = self.str2lst(self.plaintext)
... |
import sys
import math
import re
def inToStr(numb,base):
convertString = "0123456789AB"
if numb < base:
return convertString[numb]
return inToStr(numb//base,base)+convertString[numb%base]
n = int(input())
dict={"Jan":"0",
"Feb":"1",
"Mar":"2",
"Apr":"3",
"May":"4",
"J... |
#!/usr/bin/env python
# Muller's method
# made by: Jordan Winkler
# finds an approximation of a root using Muller's method
# This program is weak against injection attacks.
# option -f for fractions, default floating point
# -d for debugging or verbose mode
# -i [number] for iterations of function
# ... |
# 2D dictionary of tasks to be done
tasks = {'t1': {'todo': 'Call John for AmI project organization', 'urgent': True},
't2': {'todo': 'buy a new mouse', 'urgent': True},
't3': {'todo': 'find a present for Angelina’s birthday', 'urgent': False},
't4': {'todo': 'organize mega party (last week o... |
"""Eliminar duplicados
Crea una función que dada una lista cualquiera, devuelva una copia de
esta lista eliminando los elementos duplicados. """
Lista= [1, 2, 3, 4, 3, 2, 5, 6, 6, 7, 9, 9, 7, 5, 4, 3]
Lista_2= ["Rojo","Verde","Marron","Negro","Blanco","Negro","Rojo"]
def mostrarListraSinRepetidos(lista):
return ... |
""" Lanzador de dados
Existen diferentes tipos de dados, según el número de caras de estos.
De 4, de 6, de 8, de 10, de 12 y de 20 caras.
En juegos que utilizan estos dados, se usa una notación concreta para
decir cuandos datos hay que lanzar y de que tipo:
-"1d6" para indicar un dado de 6 caras
-"3d4" para lanz... |
class Mensaje():
def __init__(self,contenido):
self.Contenido=contenido
self.Enviados=[]
self.Recibidos=[]
self.Abiertos=[]
self.Abierto=False
#Añade a la lista enviados el id de usuario
def añadirEnviado(self,id_Us):
self.Enviados.append(id_Us)... |
if True:
print "In if condition"
if True:
print "In nested if"
else:
print "In nested else of if"
elif False:
print "In else if condition of if"
else:
print "else of elif"
listex=["kaushal",2,3.5]
print listex
for i in listex:
print i
element=[]
for i in range(0,6... |
fruits = ["mango", "orange", "apple", "apple"]
print(fruits)
print(len(fruits))
print(fruits[0])
print(fruits[-3])
print(fruits[2:5])
if "orange" in fruits:
print("Yes, present!!")
fruits[-3] = "kiwi"
print(fruits)
fruits.insert(3, "banana")
print(fruits)
fruits.append("grapes")
print(fruits)
veg = ["brinjal"... |
name = 'Ranjith'
print(len(name))
print(name.count('a'))
print(name.upper()) # original string won't be modified
print(name.lower())
print(name.find('j'))
print(name.find('H')) # find returns index
print(name.find('an'))
print(name.replace('ji', 'gi'))
print('jith' in name) # checks contains
print('jith' not in nam... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from typing import List, Tuple
def readfile() -> List[Tuple[int,int]]:
contents: List[Tuple[int,int]] = []
with open('input.txt', 'r') as f:
for line in f:
split_line: List[str] = line.split(', ')
contents.append((i... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
#Iterative Approach
prevNode = head
iterNode = head
while iterNode... |
# @author: coderistan
#
# Insertion sort with Python
# Time Complexity
#
# +---------+-----------+---------+
# | Best | Average | Worst |
# +---------+-----------+---------+
# | Ω(n) | Θ(n^2) | O(n^2) |
# +---------+-----------+---------+
def insertion_sort(array):
for i in range(1,len(... |
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7,8,9,10]
y=[2,4,5,7,6,8,9,11,12,12]
plt.scatter(x,y,label="stars", color="red", marker="*",s=30)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('Scatter plot')
plt.legend()
plt.show()
|
a,b,c=[int(input()) for i in range(3)]
if a==b and b==c:print("equilateral")
elif a==b or b==c or c==a: print("isosceles")
else:print("scalene")
|
input()
print(*[i for i in input().split() if i[0]==i[-1]])
|
import turtle
import math
import random
def troca(pal):
pares = pal[::2]
impares = pal[1::2]
nova = ''
for i in range(len(pal)//2):
nova += impares[i] + pares[i]
if len(pal) % 2 != 0:
nova += pares[-1]
print nova
# zen
def zen1(raio):
#circulo grande
turtle.setheading... |
#Rosalind.info/problems/
#20200716
"""
#1. counting DNA nucleotides, .count
seq=input("input DNA sequence")
print(seq.count('A'),seq.count('C'),seq.count('G'),seq.count('T'))
#2.Transcribing DNA into RNA .replace
seq=input("input DNA sequence")
print("RNA sequence : ",seq.replace("T","U"))
#3. Complementing a Stra... |
import sys
import json
def read_txt(file_name:str)->str:
ret=""
with open(file_name,'r') as handle:
for line in handle:
if line.startswith(">"):
continue
ret += line.strip()
return ret
if __name__=="__main__" :
if len(sys.argv) !=2:
print("#usag... |
'''
Examples of working with JSON
KTN 2013 / 2014
'''
import json
'''
Converting a dictionary object to a JSON string:
'''
my_value = 3
my_list = [1, 2, 5]
my_dict = {'key': my_value, 'key2': my_list}
my_dict_as_string = json.dumps(my_dict)
print my_dict_as_string
'''
Output:
{"key2": [1, 2, 5], "key1": 3}
'''
'''
Co... |
import math
#Evalua la funcion en un punto de x
def F(x):
return (math.cos(x))**2
#Evalua el valor de la derivada en un punto de x
def f(x):
#Valor cercano a cero
h=0.0000000000000000000000001
return math.ceil((F(x+h)-F(x+0.00000))/h)
#Calula la recta tangente
def rectangente(x,m):
... |
#Question-2(a)- for Mid-point method
from mylib import *
def f(x):
return x/(x+1)
print("For Mid-point method")
print("N"," ","Result"," ","Analytical value")
midpoint_5 = midpoint(f,1,3,5)
print("5"," ",midpoint_5, " ","1.306852819440055")
midpoint_10 = midpoint(f,1,3,10)
print... |
#1: out of place approach
#2: using math
def which_appears_twice(list_of_integers):
new_list = []
for item in list_of_integers:
if item not in new_list:
new_list.append(item)
else:
return item
def which_appears_twice_math(list_of_integers, list_of_integers_with_repeated_n... |
# simply walk through the stack and find the max element.
#This takes O(n) time for each call to get_max()
from Stack import *
class MaxStack:
def __init__(self):
self.base = Stack()
self.max = Stack()
def push(self, item):
if item >= self.max.peek():
self.max.push(item)
... |
"""
algo - if end_first >= start_second:
start = start_first
end = end_second
So, we could compare every meeting to every other meeting in this way,
merging them or leaving them separate. => O(n^2)
What if we sorted our list of meetings by start time?
Then any meetings that could be merged would... |
import sqlite3
# conn=sqlite3.connect(":memory:")
conn=sqlite3.connect("customer.db")
#create cursor
c=conn.cursor()
#update records
c.execute("""UPDATE customers SET first_name = 'Seem'
WHERE last_name='Arya'
""")
#commit our command
conn.commit()
#query the database
c.execute("SELECT rowid, *... |
import socket
def main():
# 1. 创建套接字
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2. 获取服务器的 ip 和 port
dest_ip = input("请输入服务器的ip")
dest_port = int(input("请输入服务器的port"))
# 3. 链接服务器
tcp_socket.connect((dest_ip,dest_port))
# 4. 获取下载的文件名字
dowen... |
#Daydayup.py
def Daydayup(Dayrate):
Dayup =1.0
for i in range(52):
for t in range(5):
Dayup =Dayup *(1+float(Dayrate))
for t in range(2):
Dayup*=(1-0.01)
Dayup*=(1+float(Dayrate))
return Dayup
Rate=0.01
while Daydayup(Rate)<37.78:
Rate+=0.001
prin... |
#se define la funcion que recibe dos parametros
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "Usted tiene %d quesos!" % cheese_count
print "Usted tiene %d cajas de galletas!" % boxes_of_crackers
print "Eso es suficiente para una fiesta!"
print "Consigue una manta.\n"
#Se mues... |
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
#The third (3rd) animal.(ordinal) peacock
print animals[2]
#The first (1st) animal.(ordinal) bear
print animals[0]
#The animal at 3.(cardinal) kangaroo
print animals[3]
#The fifth (5th) animal.(ordinal) whale
print animals[4]
#The anima... |
from sys import argv
script, user_name = argv
prompt = '> '
#se usa el prompt para indicar que se esta esperando una orden
print "Hola %s, yo soy %s script." % (user_name, script)
print "Me gustaria que respondieras unas preguntas."
print "Te caigo bien %s?" % user_name
likes = raw_input(prompt)
print "Dond... |
"""
Author: Sidhin S Thomas
Email: Sidhin.thomas@gmail.com
Simple linear regression
The data set used to test is :
http://openclassroom.stanford.edu/MainFolder/courses/MachineLearning/exercises/ex2materials/ex2Data.zip
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT ... |
# -*- coding: utf-8 -*-
import numpy as np
import random as r
__all__ = ['Interval','I','Logical']
class Interval():
"""
Interval
---------
An interval is an uncertain number for which only the endpoints are known, for example if :math:`x=[a,b]`
then this can be interpreted as :math:`x` being be... |
"""
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 ... |
"""
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, find the shortest d... |
"""
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[... |
"""
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: tr... |
"""
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modi... |
"""
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections.
The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]... |
"""
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
"""
from .tree_node import TreeNode, root
def binary_tree_postorder_traversal(roo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.