text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-05-10
Last_modify: 2016-05-10
******************************************
'''
'''
Given an array nums, write a function to m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-07
Last_modify: 2016-01-07
******************************************
'''
'''
Given a string S, find the longest palindr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
nums = [3, 4, 4, 5, 1, 1, 1, 2, 2, 3]
target = 2
sol = Solution()
res = sol.search(nums, target)
print(res)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
from solution import ListNode
def mkListNode(nums):
"""
:type: nums: List
:rtype: ListNode
"""
head = lnp = ListNode(0)
for i in range(len(nums)):
lnp.next = ListNode(nums[i])
lnp = lnp.next
return ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-22
Last_modify: 2016-03-22
******************************************
'''
'''
Given a positive integer,
return its corre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-11
Last_modify: 2016-03-11
******************************************
'''
'''
Given two words (beginWord and endWord),
a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-05-18
Last_modify: 2016-05-18
******************************************
'''
'''
Given a string which contains only lowerca... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
s = "hello"
sol = Solution()
res = sol.reverseString(s)
print(res)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-05
Last_modify: 2016-03-05
******************************************
'''
'''
Two elements of a binary search tree (BST)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-26
Last_modify: 2016-01-26
******************************************
'''
'''
Given a linked list, swap every two adjace... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-05-07
Last_modify: 2016-05-07
******************************************
'''
'''
Given an array containing n distinct numbe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-11
Last_modify: 2016-01-11
******************************************
'''
'''
Implement regular expression matching with... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-17
Last_modify: 2016-02-17
******************************************
'''
'''
The count-and-say sequence is the sequence... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-11
Last_modify: 2016-03-11
******************************************
'''
'''
Given two words (beginWord and endWord),
a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-28
Last_modify: 2016-02-28
******************************************
'''
'''
Write an efficient algorithm that searches... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-24
Last_modify: 2016-03-24
******************************************
'''
'''
Given a binary tree, imagine yourself stan... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
# nums1 = [1, 2, 2, 3, 1]
# nums2 = [2, 3]
# nums1 = [1, 2]
# nums2 = [1, 1]
nums1 = [1, 1, 2]
nums2 = [1, 1]
sol = Solution()
res = sol.intersection(nums1, nums2)
print(res)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-08
Last_modify: 2016-03-08
******************************************
'''
'''
Given a binary tree, determine if it is he... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-17
Last_modify: 2016-03-17
******************************************
'''
'''
Given a string s and a dictionary of words... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Codec
from solution import TreeNode
def createNode(s):
s = s.strip()
if s == '#':
return None
else:
return TreeNode(int(s))
def createTree(data):
q = []
data = data.split(",")
root = createNode(data[0]);
q.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-24
Last_modify: 2016-03-24
******************************************
'''
'''
Given a range [m, n] where 0 <= m <= n <= ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-29
Last_modify: 2016-02-29
******************************************
'''
'''
Given a set of distinct integers, nums, re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-27
Last_modify: 2016-02-27
******************************************
'''
'''
Given two words word1 and word2,
find the ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-04
Last_modify: 2016-01-04
******************************************
'''
'''
You are given two linked lists representi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-18
Last_modify: 2016-01-18
******************************************
'''
'''
Given an array S of n integers, are there ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-24
Last_modify: 2016-02-24
******************************************
'''
'''
Given a m x n grid filled with non-negativ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import Solution
nums = [1, 2, 3, 4, 5, 6]
k = 11
sol = Solution()
res = sol.rotate(nums, k)
print(nums)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-05-15
Last_modify: 2016-05-15
******************************************
'''
'''
Say you have an array for which the i-th e... |
#!/usr/bin/env python3
import fileinput
from itertools import chain
from collections import defaultdict, namedtuple
programs = {}
Program = namedtuple('Program', ['weight', "children"])
for line in fileinput.input():
line = line.strip().split(maxsplit=3)
name, weight = line[0], int(line[1].strip('()'))
i... |
#!/usr/bin/env python3
import fileinput
from operator import add
move = {
"n": ( 1, 0, -1),
"ne": ( 1, -1, 0),
"se": ( 0, -1, 1),
"s": (-1, 0, 1),
"sw": (-1, 1, 0),
"nw": ( 0, 1, -1)
}
cur = (0, 0, 0)
furthest = 0
for line in fileinput.input():
for d in line.strip().split(','):... |
import re
import login
def reg():
print("register")
firstname = input("Please enter a firstname: ")
lastname = input("Please enter a lastname: ")
newemail = input("your email: ")
while not re.match(r"^[a-zA-Z][a-zA-Z0-9\.]+\@[a-zA-Z]+\.[a-zA-Z]{3}", newemail):
newemail = input("y... |
"""
COMS W4701 Artificial Intelligence - Programming Homework 1
In this assignment you will implement and compare different search strategies
for solving the n-Puzzle, which is a generalization of the 8 and 15 puzzle to
squares of arbitrary size (we will only test it with 8-puzzles for now).
See Courseworks for detai... |
str1 = 'Ab,c,de!$' # Expected output "ed,c,bA!$"
temp_str = ''
for i in str1:
if i.isalpha():
temp_str = i + temp_str
print(temp_str) # "edcba"
cnt = 0
out_str = ''
for i in str1:
if i.isalpha():
out_str = out_str + temp_str[cnt]
cnt+=1
else:
out_str = out_str + i
print(out_s... |
#write a code to find the cube of a number.Take the input from user using input() and also using command line.
#num = int(input('Enter a integer number: '))
import sys
num = int(sys.argv[1])
cube_num = num ** 3
print(cube_num)
'''
from cmd run this program like this
D:\pythonPrograms>python "program using sys module... |
str1 = 'aaabbab' # expected output should be a3b2a1b1; string compression
count = 0
temp = None
comp_str1 = ''
for i in str1:
if temp is None:
temp = i
count += 1
continue
if temp == i:
count += 1
#comp_str1 = comp_str1 + temp + str(count)
else:
comp_str1 = c... |
from bobocep.receiver.validators.bobo_validator import \
BoboValidator
class StrDictValidator(BoboValidator):
"""A validator that checks whether data is a dict, where both the keys and
values are of type str.
:param min_length: The minimum length for strings, defaults to 0.
:type min_length: int,... |
pos = -1
def binarysearch(list,n,low,high):
if low > high:
return False
else:
mid = (low + high)//2
if list[mid] == n:
globals()['pos'] = mid
return True
else:
if list[mid] < n:
return binarysearch(list,n,mid+1,high)
... |
#-*-coding:utf-8-*-
'''
set类型使用实例
'''
__author__ = 'long'
import sys
import os
if __name__=="__main__":
li=os.listdir(".")
print li
if "hello.txt" in li:
os.rename("hello.txt","hi.txt")
elif "hi.txt" in li:
os.rename("hi.txt","hello.txt")
#把后缀为html的改为htm后缀的文件
files=os.listdir("... |
#-*-coding:utf-8-*-
'''
列表内涵
列表内涵的一般形式如下,我们可以把[]内的列表内涵写为一行,也可以写为多行。
[表达式 for item1 in 序列 1 … for itemN in 序列 N if 条件表达式]
上面的表达式分为三部分,最左边是生成每个元素的表达式,然后是 for 迭代过程,最右边可以设定一个 if
判断作为过滤条件。
'''
__author__ = 'long'
import sys
def func():
x=1
y=2
m=3
n=4
sum=lambda x,y,:x+y
print sum
sub=lambda m,n:... |
#-*-coding:utf-8-*-
'''
python 函数例子
'''
import sys
import random
def Main():
def F1():
print "我是F1"
def F2(x,y):
a=x+y
return a
#定义有多个返回值的函数,用逗号分割不同的返回值
#返回结果是一个元组
def F3(x,y):
a=x/y
b=x%y
return a,b
def compareNum(num1,num2):
if(num1>num2):
... |
WORDS_PATH = "words.txt"
TEXT_PATH = "text.txt"
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’"
def clean_word(word):
"""
String -> String
produce string with all character deleted despite letters(lower/upper case)
"""
clear_word = ""
for char in word:
if char in letters:
cl... |
infile = open("score.txt", "r") #읽기 모드로 파일 객체 생성
outfile = open("avg.txt", "a") #추가 모드로 파일 객체 생성
def average(list): #평균을 구하는 메소드
sum=0
for i in range(1,4):
sum += int(list[i])
return sum/(len(list)-1)
s = infile.readline() #한 줄씩 읽기
s = s.rstrip() #개행 문자 삭제
list1 = s.split(", ") #... |
import time
from binary_search_tree import BinarySearchTree
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the... |
def convertHexToDec(hexSubString):
return str(int(hexSubString, 16))
hexaString = ""
while hexaString != "exit":
hexaString = input("What is the hex?: ")
if hexaString == "exit":
quit()
hexaString.replace(" ", " ")
outString = ""
if len(hexaString) % 2 == 0:
for i... |
# There are comments with the names of
# the required functions to build.
# Please paste your solution underneath
# the appropriate comment.
# factorial
def factorial(n):
if n<0:
raise ValueError
if n <= 1:
return 1
return n * factorial(n-1)
# reverse
def reverse(in_str):
if in_str ==... |
# Uses python3
def edit_distance(s, t):
# write your code here
return 0
def levenshtein_distance(s1, s2):
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1, c1 in enumerate(s1):
if c1... |
from copy import deepcopy
class Player:
def __init__(self, name):
self.name = name
self.last_move = None
def first_move(self):
return self.last_move == None
def __repr__(self):
return 'Player ' + self.name + ', Last Move: ' + str(self.last_move)
class GameState:
def ... |
a = [2, 8, 10, 15, 17, 7]
max = max(a)
for i in a:
if (i % 2) == 1:
print(i + max)
|
import pandas as pd
print("\t\tBlood Donor Organization\n")
a = int(input("If Admin press 1\nIf User press 2\n"))
HospitalName = []
BloodGroupAvailable = []
Phno = []
Donorname = []
Donorphno = []
DonorBloodgroup = []
Address=[]
Email=[]
def addhospital():
a = input("HospitalName")
b = inpu... |
import turtle
turtle.shape('turtle')
turtle.pendown()
turtle.left(90)
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(125)
turtle.right(90)
turtle.forward(150)
turtle.right(90)
turtle.forward(150)
turtle.right(90)
turtle.forward(15)
turtle.right(90)
turtle.forward(150)
turtle.rig... |
# Write a Python function frequency(l) that takes as input a list of integers and returns a pair of the form (minfreqlist,maxfreqlist) where
# minfreqlist is a list of numbers with minimum frequency in l, sorted in ascending order
# maxfreqlist is a list of numbers with maximum frequency in l, sorted in ascending
# For... |
# A square n×n matrix of integers can be written in Python as a list with n elements, where each element is in turn a list of n integers, representing a row of the matrix. For instance, the matrix
# 1 2 3
# 4 5 6
# 7 8 9
# would be represented as [[1,2,3], [4,5,6], [7,8,9]].
# Write a function rotate(m) t... |
#exponentiation by square & multiply
"""
Created on Wed Jun 14 15:57:39 2017
@author: 1f604
"""
import cProfile
def to_bits(n): #this method is quite inefficient
bits = []
while(n):
bits.append(n%2)
n /= 2
return list(reversed(bits))
def to_bits2(n): #this method is even more inefficien... |
import sys
import glob
def main():
'''prints names of all files with sys.argv as suffix'''
assert len(sys.argv) >= 2, 'Argument list cannot be empty'
suffix = sys.argv[1] # NB: behaviour is not as you'd expect if sys.argv[1] is *
glob_input = '*.' + suffix # construct the input
glob_output = glob.g... |
h=10
r=5
f=15
Vtank=3.14*(r)**2*h
t=int(input('Enter time='))
Vwater=f*t
if Vwater>Vtank:
print('Overflow')
print('Volume',Vwater-Vtank)
elif Vwater==Vtank:
print('Fill')
else:
print('Underflow')
ht=Vwater/(3.14*(r)**2)
hr=h-ht
print('Filled height=',round(ht,2),'Remaining height=',round(hr,2))
|
num = input("enter a number: ")
num = intut()
newnum = int(num)
if (num > 100):
print ("Raptors Win")
elif (num > 100):
print ("Bah")
else:
print ("100") |
from tkinter import *
master = Tk()
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
entry.bind('<Return>', return_entry)
mainloop() |
from IPython.display import clear_output
from sys import exit
#NOTE: Global variables
mark1 = 'X'
mark2 = 'O'
board_position = ['1', '2', '3', '4', '5', '6', '7', '8' , '9']
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def render_board():
clear_output()
print(board[6], "|", board[7], "|", board[8]... |
import numpy as np
def bisection(f,a,b,TOL,NMAX):
# THIS FUNCTION PRINTS THE a,b,c VALUES FOR EACH ITERATION:
#Approximates root using Bisection Method
#In an interval[a,b] with a tolerance TOL
#|f(c)| < TOL, where m is the midpoint
#INPUT : f , a , b , TOL , NMAX
# f : fu... |
import matplotlib.pyplot as plt
import numpy as np
import math
t = np.linspace(0, 3*math.pi,1001)
x = np.multiply(t,np.cos(t))
y = np.multiply(t,np.sin(t))
#plt.xlim([-100, 10])
#plt.ylim([-100,-100])
plt.plot(x,y)
plt.axis()
plt.title("plot of parametric function")
plt.show()
|
#! python3
# phone_email.py - This will find any phone numbers and email addresses on a certain file
import pyperclip, re
with open('names.txt', 'r') as file:
filename = file.read()
def phoneExtractor(filename):
phoneRegex = re.compile(r'''
(?P<phone>\(?\d{3}\)?\s?.?-?\d{3}\s?-?.?\d{4}) #Phone
''', re.X|re.... |
"""
GeoProject for Python v. 1.1
Coded by Kuba Siekierzynski 2016-2017
Original code:
https://code.sololearn.com/c57gr6Ay31s9/#py
GeoProject is a small demonstration on how to use Google API in Python for some geolocation fun :)
Added in v. 1.1:
- better formatting
For mobile, I recommend downloading QPython3, copy ... |
"""
Create your own module v. 1.0
Coded by Kuba Siekierzyński (c) 2017
Original code:
https://code.sololearn.com/cLF0P3C3eZ52/#py
Inspired by Given and Kasimayan :)
https://www.sololearn.com/discuss/645722/?ref=app
The code shows in a few steps how to create your own module in Python and later import a method from i... |
class Trie(object):
def __init__(self):
self.trie = {}
def insert(self, word):
trie = self.trie
for c in word:
trie = trie.setdefault(c, {})
trie['word'] = word
def search(self, word):
trie = self.trie
for c in word:
if... |
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
#test case nums = [5,4,0, 3, 1, 6, 2] -> nums[0]->nums[5]->nums[6]->nums[2] ->max is 4 return 4
#1. brute force -> iterate over the array for each element for a new loop until meeting their first element, res = max(res, count) return... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
#two pointer: let slow goes to middle and fast goes to the end (!= null)
# slow: 1x, fast: 2x for... |
# Definition for a binary tree node.
from lib2to3.pgen2.pgen import DFAState
from tkinter.tix import Tree
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution: #time O(n): for hashmap + recursive tree(each nod... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
... |
def prodispalindrome(n1, n2):
n = n1 * n2
return str(n) == str(n)[::-1]
def palindrome(n):
return str(n)[::-1]
def maxpalindrome():
for i in reversed(xrange(100,999)):
for j in reversed(xrange(100,999)):
if prodispalindrome(i, j):
yield i * j
print max(maxpalindro... |
import csv
csvpath = "budget_data.csv"
#def financial_analysis(data_group):
print("Financial Analysis")
print("---------------------------")
with open(csvpath, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
# print(f"Name:{csv_header}")
total ... |
def triangle_number_generator():
for n in range(1,1000000):
yield n*(n+1)//2
def count_divisors(n):
return sum([2 for i in range(1,int(n**0.5)+1) if n%i==0 and i*i != n])
print(next(i for i in triangle_number_generator() if count_divisors(i) > 500))
|
a = 3
result = 0
while a < 1000:
if(a % 3 == 0 or a % 5 == 0):
result += a
elif(a % 15 == 0):
result -= a
a += 1
print(result)
|
# importing the libraries
from bs4 import BeautifulSoup
import requests
import csv
# Step 1: Sending a HTTP request to a URL
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
# Make a GET request to fetch the raw HTML content
html_content = requests.get(url).text
# Step 2: Parse the html cont... |
'''
Problem:
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N?
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
'''
from __future__ import print_function, division
import math
def isprime(no):
if(no==2):
return True
elif (no%2=... |
def fibonacci_genrator():
a, b = 0,1
while True:
a,b = b,a+b
yield b
answer = 1
gen = fibonacci_genrator()
while len(str(next(gen))) < 1000:
answer += 1
assert answer+1 == 4782
|
# Via https://www.dev2qa.com/how-to-download-image-file-from-url-use-python-requests-or-wget-module
# Import requests, shutil python module.
import requests
import shutil
# This is the image url.
image_url = "https://www.dev2qa.com/demo/images/green_button.jpg"
# Open the url image, set stream to True, this will re... |
from math import sqrt
def nextSqure(n):
# 함수를 완성하세요
x='no'
if int(sqrt(n))==sqrt(n):
x=(sqrt(n)+1)**2
return x
# 아래는 테스트로 출력해 보기 위한 코드입니다.
print("결과 : {}".format(nextSqure(1036355))); |
"""
This file demonstrates how the SentimentAnalyzer class is used to generate a sentiment score for a selection of topics
such as bidne & trump
"""
# !/usr/bin/env python3
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from collections import defaultdict
from nltk.parse.corenlp import CoreNLPDependencyPa... |
__author__ = 'Elena'
from random import randint
def generate_list(n, min, max):
"""
Generates list of N integers in range from x to y
"""
l = []
for i in range(n):
num = randint(min, max)
l.append(num)
return l
def find(l, sum):
"""
Finds all pairs of elements from t... |
class Node:
def __init__(self, data=None, meaning=None):
self.data = data
self.right = None
self.left = None
self.eq = None
self.meaning = meaning
class TST:
def __init__(self):
self.root = None
def insert(self, node, word, meaning):
if node is N... |
import string
def count_the_article():
str1 = []
fout = open('book1.txt', 'r')
r = fout.readlines()
for line in r:
str2 = line.lower().strip(string.punctuation + string.whitespace)
str1 += str2
total = {}
for word in str1:
total[word]... |
'''
api.py
Yitong Chen, Megan Zhao, Eva Zhong Feburary 1, 2017
This API contains routines that queries the database for information.
'''
import flask
from flask import render_template
import json
import sys
import psycopg2
import getpass
import re
app = flask.Flask(__name__)
database = 'zhonge'
user = 'z... |
d=float(input('Please enter what is your initial balance: \n'))
p=float(input('Please input what is the interest rate (as a number): \n'))
d=float(d+d*(p/100))
year=1
while year<=5:
d=float(d+d*p/100)
print('Your new balance after year:',year,'is',d)
year=year+1
print('your final year is',d)
|
# Problem 2
# 피보나치 수열의 각 항은 바로 앞의 항 두 개를 더한 것이 됩니다.
# 1과 2로 시작하는 경우 이 수열은 아래와 같습니다.
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# 짝수이면서 4백만 이하인 모든 항을 더하면 얼마가 됩니까?
fibonacci = [1, 2]
result = 0
for i in range(1, 100):
next_fibonacci = fibonacci[i-1] + fibonacci[i]
if next_fibonacci >= 4000000:
for i in ... |
import numpy as np
from numpy.polynomial.chebyshev import chebval
class ChebyshevApproximant(object):
def __init__(self, function, window, degree=6, nevalpts=None,
function_args=(), function_kwargs={}):
"""1D Chebyshev approximation / interpolation.
For a vector function, ```func... |
numbers = [1, 2, 3, 4, 5, 6, 7]
even = []
odd = []
while len(numbers) > 0:
number = numbers.pop()
if number % 2 == 0:
even.append(number)
else:
odd.append(number)
fruits = ["apple", "orange", "banana"]
for index in range(len(fruits)):
print fruits[index]
|
#!/usr/bin/env python3
import colors as c
(c.clear)
print(c.red + 'Hi,whats yours name?')
name = input("your name")
print(c.red + 'well hi there')
|
"akrham seris recap"
import colors as c
from utils import ask
intro = c.magenta + '''welcome
to the pink fluffy unicorns quiz.
let's test your knowlege...'''
def q1():
answer = ask("who was the failed robin")
if answer == "jason tood":
return True
return False
def q2():
answer = ask("who i... |
class Car(object):
def __init__(self,model,color,company,speedlimit):
self.model=model
self.color=color
self.company=company
self.speedlimit=speedlimit
def start(self):
print("started")
def stop(self):
print("stopped")
def accerelate(se... |
def sorted1D(dlist):
totlist=[]
for i in range(0,len(dlist)):
for j in range(0,len(dlist[i])) :
totlist.append(dlist[i][j])
totlist.sort()
return totlist
print(sorted1D([[1, 2, 5, 4], [1, 2, 3, 4]])) |
def listMaxCols(dlist):
maxlist=[]
for i in range(0,len(dlist[0])):
max = 0
for j in range(0,len(dlist)):
if dlist[j][i] > max:
max = dlist[j][i]
maxlist.append(max)
return maxlist
print(listMaxCols([[1, 2, 5, 4], [1, 2, 3, 4]])) |
def monthly_loan_amt(principal, annual_interest_rate, duration):
r = (annual_interest_rate/100)/12
n=duration*12
if(annual_interest_rate == 0):
return principal/n
pval = pow((1+r),n)
return principal * ((r*pval)/(pval-1))
def loan_balance(principal, annual_interest_rate, duration,... |
def sum2D(dlist):
tot = 0
cnt = 0
for i in range(0,len(dlist)):
for j in range(0,len(dlist[i])):
#print(dlist[i][j])
cnt = cnt + 1
tot = tot + dlist[i][j];
return tot/cnt
print(sum2D([[1, 2, 3, 4], [1, 2, 3, 4]])) |
def countChickenDogs(heads,legs):
chickens=0
dogs=0
while(True):
#print(chickens,dogs,heads,legs)
chickens = chickens+1
heads = heads -1
legs = legs - 2
#print(chickens,dogs,heads,legs)
if(legs >= 4 and heads >= 1 and legs != heads*2):
dogs = dogs ... |
def triangle(height):
i = height
while i >=1 :
astr="*"
if i == height or i == 2 or i==1:
print(astr*i)
else:
print(astr+" "*((i-2))+astr)
i=i-1
triangle(1) |
#Write a function named "reverse_dictionary" that receives a dictionary as input argument and returns a reverse
# of the input dictionary where the values of the original dictionary are used as keys for the returned dictionary
# and the keys of the original dictionary are used as value for the returned dictionary
d... |
list1 = ['Anna', 'Edgar']
print("List1 =",list1)
list2 = ['Eliza', 'Ani', 'Vardan']
print("List2 =",list2)
def decorator(func):
def wrapper(*arg, **kwargs):
print("List1 befor append:",list1)
func(*arg,**kwargs)
print("List1 after append:",list1)
return(wrapper)
@decorator
def add_values(list2):
for i in ran... |
list1 = [[5, 7, -7, 'abc'], [2, 4, True, 3], [4, 6, 7, 7], [2, 4, 1, True]]
print("List1 = ",list1)
a = 0
for i in range(len(list1)):
if a == 1:
break
for j in range(len(list1[0])):
if list1[i][j] == 3:
a=1
break
print("list1[i][j] = ",list1[i][j]) |
def is_panidrome(text):
reversed_string = text[::-1]
if text == reversed_string:
print(True)
else:
return print(False)
is_panidrome(str(input())) |
#Import the necessary methods from tweepy library
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import pandas as pd
import matplotlib.pyplot as plt
#Variables that contains the user credentials to access Twitter API
access_token = "1518... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.