text stringlengths 37 1.41M |
|---|
import re
# Convert text to lower-case and strip punctuation/symbols from words
def normalize_text(text):
norm_text = text.lower()
norm_text = re.sub(r"\.+", ".", norm_text)
# Replace breaks with spaces, in case there's broken html in there
norm_text = norm_text.replace('<br />', ' ')
# Replace m... |
"""
nums = []
for x in range(8):
nums.append(x)
print nums
squares = []
for x in range(8):
squares.append(x**2)
print squares
print [x for x in range(8)]
print [x*x for x in range(8)]
print [ (x, x*x, x*x*x) for x in range(8) ]
p="myNoobPass1234"
print [x for x in p]
print [x for x in "1234"]
UC_LETT... |
import functools
class A(object):
def __init__(self,k="do"):
self.k=k
def __call__(self, func):
@functools.wraps(func)
def __de(*args,**kwargs):
if self.k=="do":
self.notify(func)
return func(*args,**kwargs)
return __de
def notify(self,... |
n = 10
# Iterative
x=1
y=1
for i in range(1, n):
oldx=x
x=y
y=oldx+y
print(x)
# Recursive
def fibbonaci(n):
if n<=1:
return 1
else:
return fibbonaci(n-1) + fibbonaci(n-2)
print(fibbonaci(n))
|
def SEARCH(brr,Num):
Cnt=0
for i in range(len(brr)):
if brr[i]==Num:
Cnt+=1
return Cnt
def main():
arr=[]
for i in range(int(input("ENTER THE NUMBER OF ELEMENTS IN ARRAY"))):
print("ENTER THE ARRAY ELEMENT ",i+1)
arr.append(int(input()))
print("ANSWER IS : "... |
def PRIME(iNo):
for i in range(2,int(iNo/2+1)):
if iNo%i==0:
print("IT IS NOT A PRIME NUMBER")
break
else:
print("IT IS PRIME NUMBER")
def main():PRIME(int(input("ENTER THE NUMBER")))
if __name__ == "__main__":
main() |
def CHKEVEN(iVal):
if(iVal%2==0):
return True
else:
return False
def main():
no=int(input("ENTER THE NUMBER "))
ret=CHKEVEN(no)
if ret == True:
print("EVEN")
else:
print("ODD")
if __name__ == "__main__":
main() |
import math
from sympy import * #for differentiation & mathematical functions
import numpy as np #matrix operations
pi=3.141592653589793
e=2.718281828459045
print('Project for "Numerical analysis". under the supervision of Dr. Mahmoud Gamal')
print('by:')
print('\t\tMohamed Yosry ElZarka 19100')
print('\t\t... |
# Python 3.6
# comparison of two versoin numbers in string
# Invoke: versionNumCompare(VersionNumInString, VersinNumInString)
# Return: return True if first version is greater than second,
# otherwise, return False
def versionNumCompare(verStr1, verStr2):
verFloat1 = float(verStr1)
verFloat2 = float(ve... |
#!/usr/bin/python
a = 1
b = 2
c = 997
while(a < 332):
while(b < c):
if(a**2 + b**2 == c**2):
print "Found it: " + str(a * b * c)
print "a=" + str(a) + " b=" + str(b) + " c=" + str(c)
exit()
b = b + 1
c = c - 1
a += 1
b = a + 1
c = 1000 - (a + b) |
from matplotlib import pyplot as plt
#x_number = [1,2,3,4,5]
x_number = list(range(1,5001))
y_number = [x**3 for x in x_number]
#edgecolor边框 c y渐变camp颜色
plt.scatter(x_number,y_number,edgecolors='none',c=y_number,cmap=plt.cm.Blues)
#坐标 标题
plt.title("Cube Number",fontsize=15)
plt.xlabel("value",fontsize=12)
plt.ylabel("... |
A=10
B="HelloPython"
C=6.9999
D=1+2j
#datatypes print datatypes
print("A-"+str(A))
print("B-"+str(B))
print("C-"+str(C))
print("C-"+str(D))
#get data types
print("A type is ",end="")
print(type(A))
print("B type is ",end="")
print(type(B))
print("C type is ",end="")
print(type(C))
print("D type is ",end="")
print(ty... |
"""Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
c... |
#字典
my_dic={"lisirui":110,"zhangkaiyan":120,"wanghanwei":119}
print(my_dic["lisirui"])
print(len(my_dic))
print("zhangkaiyan" in my_dic)
for key in my_dic :
print(key)
|
#python中的生成器
g = (x * x for x in range(10))
#可以用g 中自带的函数next来访问每一个元素next(g)
#也可以用循环(方便)
for n in g:
print(n)
#===========================================================
#generator的函数,在每次调用next()的时候执行,
#遇到yield语句返回,再次执行从上次返回的yield语句处继续执行
#generator函数的“调用”实际返回一个generator对象
def fib(max):
n, a, b = 0, 0, 1
while n < m... |
def limitLabel(limit):
for i in range(0,limit+1):
if i % 2 == 0:
print(i, "EVEN")
else:
print(i, "ODD")
inp = eval(input("Please enter the limit range: "))
limitLabel(inp)
|
def str_to_Int(str1,str2):
i1 = int(str1)
i2 = int(str2)
i3 = i1 + i2
print("Addition of these no.s: ", i3)
strInp1 = input("Please enter 1st number: ")
strInp2 = input("Please enter 2nd number: ")
str_to_Int(strInp1,strInp2)
|
'''
def strUpper(str):
li = []
while str != "":
li.append(str.partition(" ")[0])
str = str.partition(" ")[2]
for i in li:
i.upper()
str2 = ' '.join(li)
return str2
'''
inpStr = input("Please enter your string: ")
##print(strUpper(inpStr))
print(inpStr.upper())
|
"""
This module contains the Background, Stage and Viewport classes.
Viewport: The viewport is the area of the stage visible on the display surface.
Stage: The stage is the area of the game that is currently rendered, it contains the viewport.
Background:
"""
import pygame
from get_image import get_image
class Backg... |
# Dictionaries
# Using strings, lists, tuples and dictionaries concepts, find the reverse
# complement of AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA
read = "AAAAATCCCGAGGCGGCTATATAGGGCTCCGGAGGCGTAATATAAAA"
dict = {'C': 'G', 'G': 'C', 'A': 'T', 'T': 'A'}
complement = [dict[base] for base in read]
complement.rever... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ME 499/599 File I/O example
Bill Smart
"""
from math import factorial
if __name__ == '__main__':
# Open a file and w
# with open('fac', 'w') as f:
# for n in range(10):
# f.write('{0} {1}\n'.format(n, factorial(n)))
#
# with... |
# Import libraries
from bs4 import BeautifulSoup # Install BeautifulSoup4
from urllib.request import Request, urlopen
from statistics import variance
from datetime import datetime
#dt = datetime.strptime('May 10, 2019', '%b %d, %Y')
#st = dt.strftime('%Y-%m-%d')
# Scrape the rows from a table with a given ID
def ge... |
def median(lst):
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
def newPlayer():
score1 = float(input("Please input the first round score"))
score2 = flo... |
########################################################################
# #
# Playing moving Sound in headphones #
# #
# 1.Imported a wave au... |
for x in range(2,11,2):
print(x)
print("----------")
for x in range(1,11,2):
print(x) |
a=int(input("plz enter anum:"))
b=int(input("plz enter a num:"))
if a+b==10:
print("true")
elif a==10 or b==10:
print("true")
else:
print("false") |
def linear_search(lst, to_find):
# search for the element to_find inside lst
# if found, return index of element
# else return -1
if (to_find in lst):
return lst.index(to_find)
else:
return -1
print(linear_search([1], 1))
|
#my virtual car1.0
"""
Author::: tushar2899
following inputs required:
license plate number
vehicle identification no.
and then choice codes for continuous operation
ENTER THE DESIRED CHOICE CODE:
1.GEAR UP 2.GEAR DOWN
3.MOVE FAST 4.MOVE SLOW
5.TURN LEFT 6.TURN RIGHT 7.GO REVERSE
8.STOP 9.EXIT
"""
... |
#just run pythnon3 module_using_name.py
#Every python module has its __name__ defined.if this is __main__
#this is program stroed as a
#import sys
#sys.path -->stores as shows the following path as well
#now import this file as import module_using_name
#run as another module
if __name__ == '__main__':
... |
'''
read a file from
'''
''' data = open('text.txt','r')
for line in data:
print(line)
data.close()
'''
'''
write in a file
'''
tar = open('new_file.txt','w')
tar.write('Hey i m suresh ')
tar.write('Python')
tar.write('\n')
tar.write('finally i got')
tar.close()
tar = open('new_file.txt','a')
tar.w... |
class Player:
"""Model representing a chess player in a tournament"""
def __init__(self, id, firstname, lastname, gender, rating):
self.id = id
self.first_name = firstname
self.last_name = lastname
self.gender = gender
self.rating = int(rating)
def __str__(self):
... |
import pandas as pd
import numpy as np
df = pd.read_csv('movies_dataset.txt', encoding= 'unicode_escape')
start_year = 1950
end_year = 1960
mask = (df['year'] > start_year) & (df['year'] <= end_year)
df1 = df.loc[mask]
df_count_year = df1.count()
print("Number of movies released between the year 1950 and 19... |
###############################################################################
#Todo:
#*Make it so the size of the room can be changed easily using a roomSize variable
#*Figure out how Desika wants the exponential variable to act
#*Make number of time steps its own variable so it can be changed easier
#*Make my own ra... |
spam = ["apples", "bananas", "tofu", "cats"]
def return_string(spam):
desired_string = ''
for item in range(len(spam)):
if item == 0:
desired_string = desired_string + spam[item]
continue
elif item == (len(spam)-1):
desired_string = desired_string + " and " ... |
shopping_list_3 = []
def show_help():
print("\n Separate each item with comma ")
print("Type DONE when finish adding the list, Type SHOW to see the current list, Type HELP to see this message")
def show_list():
count = 1
for item in shopping_list_3:
print("\n {} : {}".format(count, item ))
... |
''' Give a list
remove vowel from each item in the list, untill we get exception
print out the list without vowel, with first alphabet in each word capital
'''
words = ['hello', 'ronak', 'ray', 'jaanu']
vowel = list('aeiou')
output=[]
for item in words:
name = list(item.lower())
for vw in vowel:
while ... |
def word_count(sentence):
s_lower = sentence.lower()
list_of_words = s_lower.split()
word_dict={}
for ch in list_of_words:
if ch in word_dict:
word_dict[ch] = word_dict[ch] + 1
else:
word_dict[ch] = 1
return word_dict
print(word_count("I AM awes... |
# Rui Ma V00800795
# Nannan Zhang V00809956
# The reference we used is according to this video: https://www.youtube.com/watch?v=qNdqS9t5fXc
# We changed the image color, size, and added other seven itmes:
# three flowers, a sun and its lights, a red mouth, and the drawing speed.
# In order to save marker's time, we pr... |
def encrypt(text, rot):
new_text = ""
for character in text:
new_text += rotate_character(character, rot)
return new_text
def alphabet_position(letter):
lc_alphabet = "abcdefghijklmnopqrstuvwxyz"
uc_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(len(lc_alphabet)):
if letter == lc_alphabet[i]:
ret... |
from random import randint
'''
Игра в кости. Компьютер загадывает два числа от 1 до 6(кидает кости).
Дальше кидает игрок. Так же кидает кости, если 1 - полностью совпадают - выйгрыш.
2 - если одна цифра сопадает,
3 - сумма ... |
# KUniqueCharacters(str) take the str parameter being passed and find the longest substring that contains k unique characters, where k will be the first character from the string. The substring will start from the second position in the string because the first character will be the integer k. For example: if str is "2... |
# chapter 1 exercise 8
# solve the following in Field 31
# 3 / 24
# 17 ^ -3
# 4 ^ -4 * 11
print("3 / 24 = ")
print((3 * 24 **(31-2)) % 31)
#solving, using the faster way
print("3 / 24 = ")
print(3*pow(24,31-2,31) % 31)
print("17 ^ -3 = ")
print(pow(17,31-4,31))
print("4 ^ -4 * 11 = ")
print(pow(4,31-5,31)*11%31)
#sol... |
# Con la importación traemos las librerías que necesitamos a nuestro código.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import matplotlib.backends.backend_pdf
# Importamos los datos.
data=pd.read_csv(r"monthly_salary_brazil.csv")
# De la tabla que importamos desde el csv, obtenem... |
class node():
def __init__(self, data=None, nextN = None):
self.data = data
self.nextN = nextN
class linkedHash():
def __init__(self):
self.head = node()
self.size = 0
self.tabela = [self.head]*10
def funcaoHash(self,data):
return data%10
def findNum(self,data):
self.key = self.funcaoHash(data)
a... |
import time
import datetime
print("Current date and time: " , datetime.datetime.now())
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", date... |
def dimCheck():
try:
print("st1")
print("st1")
#return 10
# '''(except only execute when try block have some error code)'''
except TypeError : #( must be child of next excepts)
print("st1")
print("st1")
return 21
except Exception : #( must be parent o... |
'''
Database
'''
'''
**************************** Dataabse Connectivity with sqlite3
'''
import sqlite3
try:
db = sqlite3.connect('pythondb')
cursor = db.cursor()
#cursor.execute(''' create table users (name text, email text, username text, password text, password text) ''')
cursor.execute('''select *... |
'''
print(values objects,seperator, end, file, buffer)
'''
print(1,2,3) #1 2 3
print('Eknayth', 123, 'hiii', 1234) #Eknayth 123 hiii 1234
print('Eknayth', 123, 'hiii', 1234,sep='__', end='$$$') #Eknayth__123__hiii__1234$$$
a=5
print("The Value is : ", a) #The Value is : 5
b=10
c="Hiii"
print("The Value is: %... |
'''
Database
'''
'''
**************************** Dataabse Connectivity with sqlite3
'''
import sqlite3
try:
db = sqlite3.connect('pythondb')
cursor = db.cursor()
# cursor.execute(''' create table users (name text, email text, username text, password text) ''')
cursor.execute('''select * from person '... |
"""This problem was asked by Amazon.
Write a function that takes a natural number as input
and returns the number of digits the input has.
Constraint: don't use any loops.
"""
# idea: use the log of ten
import numpy as np
def number_of_digit(x):
return np.floor(np.log10(x,10)) + 1
|
"""This problem was asked by Google.
Given a list of integers S and a target number k, write a function
that returns a subset of S that adds up to k. If such a subset cannot
be made, then return null.
Integers can appear more than once in the list. You may assume
all numbers in the list are positive.
For example, given... |
#Import files
import os
import csv
csvpath = os.path.join('..''Resources', 'budget_data.csv')
with open (csvpath, newline = '') as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
print(csvreader)
#Create Lists
num_months = []
net_PL_total = []
PL_change = []
Average_Change = []
#Use Next function to skip ... |
# Data Science Programming Assignment 2 : decision tree
# author : Seonha Park
# written in Python3
import DecisionTree
import TreeNode
import sys
#get label which has largest value. to estimate non-leaf ended entry
def getMaxLabel(parent_attr, this_attr, root_attr):
max_array = []
max_val = 0
#find larges... |
import numpy as np
from analysis.helpers.convolve import apply_filter
def run(image_data):
"""
Applies a Sobel filter across an image. This is essentially moving a small matrix across every pixel in the image
and calculating the gradient of the pixel's neighbors. The returned value is an image of the same... |
class Polygon:
def perimeter(self):
pass
def area(self):
pass
class Rectangle(Polygon):
def __init__(self, width, height):
self.width = width
self.height = height
def perimeter(self):
return (self.width + self.height) * 2
def area(self):
return se... |
# coding=utf-8
import random
import re
class Node:
def __init__(self, data=None, value=None):
self.data = data
self.value = value
self.left = None
self.right = None
def compare(self, a, b):
# 比较函数:
# a<b,返回负数
# a>b,返回正数
# a=b,返回0
#
... |
#Reina Irizarry
# This program will do the following:
'''Repeatedly ask the user for numbers until they enter a 0 or negative.
For each number they enter, the program will report if the number was even or odd,
whether it is a perfect square, the sum of the squares of the numbers up to
and including the number, and th... |
"""You can use this class to represent how classy someone
or something is.
"Classy" is interchangable with "fancy".
If you add fancy-looking items, you will increase
your "classiness".
Create a function in "Classy" that takes a string as
input and adds it to the "items" list.
Another method should calculate the "classi... |
import requests
print("Bem-vindo ao verificador de sites 1.0!")
print("Nenhum direito reservado.")
print("")
ficar = "s"
while ficar == "s":
print("")
urls = input("Insira as URLs dos sites que deseja verificar o status. (Separados por virgula :")
print("")
url_arr = [lista.strip() for lista in urls.split(',')]
... |
n = int(input("Введите n: "))
i = 0
n1 = n
while n1 != 0:
n1 = n1 // 10
i += 1
sum = n + (10 ** i) * n + n + (100 ** i) * n + (10 ** i) * n + n
print(f"n+nn+nnn = {sum}.")
|
# 🚨 Don't change the code below 👇
age = input("What is your current age? ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
age_as_int = int(age)
years_remaining = 90 - age_as_int
days_remaining = years_remaining * 365
weeks_remaining = years_remaining * 52
months_remaining = years_remaini... |
3 + 5
7 - 4
3 * 2
6 / 3
2 ** 3
print(3 * (3 + 3) / 3 - 3)
# PEMDASLR
# ()
# **
# * /
# + -
# PEMDAS
# Parentheses
# Exponenets
# Multiplication
# Division
# Addition
# Subtraction
# pint(2 ** 2)
# print(2 ** 3)
# print(6 / 3)
# print(type(6/3)) |
# -*- coding: utf-8 -*-
# Python的正则使用
import re
def main():
str1 = 'j1k234k11234kl1423'
# findall 使用较多
numsPattern = re.compile(r'\d{3,8}$')
nums = numsPattern.findall(str1)
print nums
# match
print re.match('^j', str1)
def matchDomain(str):
domain = ''
return domain
if __name__ ... |
# -*- coding: utf-8 -*-
# str slice
# 从索引0开始取,直到索引3为止,
# 但不包括索引3。即索引0,1,2,正好是3个元素。
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack', 'Funk', 'Zara']
print len(L)
print L[0:3]
print L[:3]
print L[1:3]
print L[2:3]
print '支持倒数的截取'
print L[-1]
print L[-2:]
print L[-2:-1]
print '#########################'
M = range(100)
... |
import itertools
import pandas as pd
import numpy as np
import warnings
# Function to take a value and a set of values to transform form a multicoding to a multiple single codings.
def conversion(value, value_set):
single_codes = -99
possible_value = -99
i = 0
running = True
while(running):
i += 1
for p in ... |
from collections import deque
def solution(priorities, location):
answer = 0
dq = deque(zip(range(len(priorities)), priorities))
prior_list = sorted(priorities)
while dq:
loc, prior = dq.popleft()
if prior_list[-1] > prior:
dq.append((loc, prior))
continue ... |
from collections import deque
'''
풀이3 : 그래프 탐색
- 양방향 네트워크
- 1번 컴퓨터가 2, 3번과 연결되어 있다면
- 2, 3번 컴퓨터와 다른 컴퓨터의 연결 상태를 탐색하고 각각 방문 처리
- 탐색이 종료되면 네트워크 카운트 +1
'''
def solution(n, computers):
visited = [False]* n
def search(x, y):
q = deque([(x, y)])
while q:
x, y = q.popleft() # x, y = q.p... |
l=[1,2,3,4,5,6,7]
print(type(l))
l=[1,2,2.3,4.5,'h','hello',[1,2,3]]
print(l)
print(type(l))
t=(1,2,3,4)
print(type(t))
s={1,2,3,4,5,6,7}
print(type(s))
print(s)
s={1,1,1,2,2,3,3,3,3}
print(s)
d={
'FirstName':'Janhavi',
'LastName':'Nandish',
'Contact':100,
101:'Ambulance'
}
print(type(d... |
print("enter the number")
x=int(input())
if x>0:
print("it is positive")
elif x<0:
print("it is negetive")
else:
print("it is zero") |
n=input()
for i in n:
if i==i.upper():
print(i.lower(),end=' ')
elif i==i.lower():
print(i.upper(),end=' ')
else:
print(i)
|
#explicit type conversion
n1=150
print("the data type of n1:",type(n1))
n2="100"
print("the data type of n2:",type(n2))
print("*****************************")
n3=n1+int(n2)
print("the data type of n3:",type(n3))
print("*****************************")
|
#sum of even and odd num
num=[2,22,27,29,35,42,8,75,88]
sume=0
sumo=0
for i in num:
if i%2==0:
sume=sume+i
else:
sumo=sumo+i
print("sum of even",sume)
print("sum of odd",sumo) |
def add(a,b):
print(f"相加{a}+{b}")
return a+b
def subtract(a,b):
print(f"相减{a}-{b}")
return a-b
def multiply(a,b):
print(f"相乘{a}*{b}")
return a*b
def divide(a,b):
print(f"相除{a}/{b}")
return a/b
print("函数做一些简单的计算")
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = d... |
print("你今年多大了",end='')
age = input()
print("你现在多高",end="")
tall = input()
print('你现在体重多少',end="")
weight = input()
print(f"所以你的年龄是{age},身高是{tall},体重是{weight}")
print("用input写的另一段")
print("这是一个猜数字游戏")
number = input("请输入初始数字:")
numbers = input("请输入你猜的数字:")
if number < numbers:
print("大了")
elif number > numbers:
... |
print("这是加法+ 100+100=",100+100)
print("这是减号- 200-100=",200-100)
print("这是除号/ 100/5=",100/5)
#除号下面计算出结果后会有一个浮点数
print("这是乘号* 100*100=",100*100)
print("这是余数的号码% 100%16=",100%16)
#%是计算余数的符号例如100%16的余数就是4
print("3+2 > 5-7",3+2 > 5-7)
print("3+2 < 5-7",3+2 < 5-7)
print("3+4 >= 4+7",3+4 >= 4+7)
print("3+4 <= 4+7",3+4 <= 4+7)... |
#print squares of these numbers
di = {0:0, 1:1, 2:2, 3:3, 4:4}
for i in di:
print i*i
squares = {x:x*x for x in range(5)} #dict comprehension with range
print squares
squares = {x:x*x for x in di} # dict comprehension with dict
print squares
'''
print ODD squares
'''
odd_squares = {x:x*x for x in range(11) if x%2==... |
"""
Collections Module
The collections module is a built-in module that implements specialized container data types providing
alternatives to Pythons general purpose built-in containers. We've already gone over the basics: dict, list, set, and tuple.
Now we'll learn about the alternatives that the collections module ... |
l = [{"Name": "Ramya", "DEPT": 1}, {"Name": "Raksha", "DEPT": 2}, {"Name":"Rashmi","DEPT":3}]
# for item in l:
# if item.keys() == "Name":
# print
# res = l[0].keys()
# res[1] = "Fullname"
# print res
res = l[0]
res["Fullname"] = res["Name"]
print res
del res["Name"]
print res
print |
a = 1
b = (1,2,3)
print id(a)
print id(b)
a=b #shallow copy, copies memry loc, a & b will be pointing to same loc
print id(a)
print id(b)
a = b[::] #deep copy, copies only value not the memory. Works for mutable objects
print id(a)
print id(b)
# >>> b = [2,3,5,6]
# >>> id(b)
# 4445651024
# >>> c = [4,5,6,7]
# >>> i... |
"""
A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
"""
from collections import defaultdict
# d = defaultdict(object)
# d["key1"] = 1
# print d.get("key1")
# print d.get("key2")
d = {"key1":1}
print d.get("key2")
"""
OrderedDict
An OrderedDic... |
l = [1,2,4,5,6,7]
# for i in range(len(l)):
# if i in l:
# # print i
# pass
# else:
# print "missing :",i
x = [i for i in range(7) if i in l]
print x
|
import sys
import os
import numpy as np
from scipy.stats import norm
import math
import random
import cv2
import run
def filter_median(image, k):
'''Filter the image using a median kernel.
Inputs:
image - a single channel image of shape (rows, cols)
k - the radius of the neighborhood you should use (posit... |
# shippig charge
weight_in_pounds = float( input('enter the amount of weight you want to ship '.title() ).strip() )
if weight_in_pounds <= 2 and weight_in_pounds > 0:
print('the shipping price is $ 1.5 '.title() )
elif weight_in_pounds <= 6 and weight_in_pounds > 2:
print('the shipping price is $ 3'.title... |
# user enter the amount of money in cent like one cent 2 cent ...
userpennies = float( input('enter the amount of pennies '.title() ).strip() )
# the amount of money in the type of 5 cent
useNrnickels = float( input('enter the amount of nrnickets '.title() ).strip() )
# the amount of money in type of 10 cents
us... |
# 1. Number Analyser
# this program print powsitve the user input is greater than 0, otherwase print
# negative if the user input is less than zero else print ;zero' if the user input is zero
# the user input
userInput = float( input('enter a number '.title() ).strip().title() )
if userInput > 0:
print(f'the... |
print("Hello World")
def insult(victim, verb, noun):
print("Hey {0}! You {1} like a {2}".format(victim, verb, noun))
insult("there", "code", "monkey")
# This is a comment, does not appear as output when running script
#Drawing a shape
print(" /|")
print(" / |")
print(" / |")
print(" /___|")
# Variables an... |
"""
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume ... |
"""
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix ret... |
size=4000000
mylist=[1];
def fibonancciList(n, k):
if k<=size:
mylist.append(k)
last=n+k
fibonancciList(k, last)
return mylist;
if __name__ == '__main__':
list=fibonancciList(1, 2)
sumt=0
for i in list:
if i%2==0:
sumt=sumt+i
print "\n",sumt
|
#SciCodeJam Problem
#Problem Week 1-A Divisibility Test
#Author Dennis Carnegie B
#function to find multiples of 7 and 11,
#and summing them up
def multipleSum(size):
sumt=0
for i in range(1, size):
if i%7==0 or i%11==0:
sumt=sumt+i
return sumt
#Main Function
def main():
print multipleSum(10000);
if __n... |
#Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3000 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line
for i in range(1999,3001):
if( (i%7 ==0) and (i%5 !=0)):
print i,"," |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 09:48:17 2018
know sth about scipy
@author: tianbiaoyang
"""
from scipy import sparse
import numpy as np
# view the version
print('numpy version: {}'.format(np.__version__))
# get data
eye = np.eye(4)
print("\nNumPy array: \n{}".format(eye))
# ... |
# -*- coding: utf-8 -*-
#>>>>>python example for tuples including named ones
""""
What: basic tuple and named_tuple stuff
Status: draft, ok draft but possibly useful
Refs:
Notes:
can add more to this
you can slice
Search on:
named
collections
*args
"""
#A tuple is defin... |
# Importing numpy library
import numpy as np
# Let a be an 2 x 2 array
a = np.array([(2,4),(3,4)], dtype = int)
# let b be an 2 x 2 array
b = np.array([(5,6),(2,6)], dtype = int)
print(a.sum())
# Array wise sum
# Output : 13
print(a.min())
# Array wise minimum value
# Output : 2
print(b.max(axis=0))
# Maximum valu... |
# String Rotation: Assume you have amethod isSubstring which checks if one word is a
# substring of another. Given two strings, 51 and 52, write code to check if 52 is a
# rotation of 51 using only one call to isSubstring (e.g.,"waterbottle"is a rotation of"erbottlewat").
#O(1) space
def stringRotation(s1, s2):
... |
class Fern:
def __init__(self, turtle):
self.turtle = turtle
turtle.left(90)
def createFern(self, size, sign):
if size < 1:
return
else:
self.turtle.forward(size)
self.turtle.right(70*sign)
self.createFern(size*0.5, -1*sign)... |
#!/usr/bin/env python3
import re
import pprint
read_chat_file = open("test_chat.txt", encoding="utf-8")
chat = read_chat_file.readlines()
frank = read_chat_file.readline()
# with open('tes.txt', 'r') as reader:
# pattern = re.compile("\d{1,2}/\d{1,2}/\d{1,2},\s\d{1,2}:\d{1,2}\s(A|P)M\s-\s\w+:")
# line = rea... |
transactions = [-100, 200, -50, 50, 40, -200, -10, 500, -30, -50]
total_expense = 0
# Your code begins
# for each transaction item
for ...:
# If the transaction amount is less than 0
if ...:
# Add the amount to total_expense
total_expense = ...
# Your code ends
print(f'Total expense: {total_expense}') |
n = 10
result = 1
# Your code begins
# While n is larger than 0
while n > 0:
# Multiply result by n
result = result * n
# Decrease n by 1
n = n - 1
# Your code ends
print(result) |
def chocolateFeast(n,c,m):
ccount = int(n/c)
wcount = ccount
while ( wcount >= m):
a = int((wcount)%(m))
wcount = int((wcount-a)/m)
ccount = ccount + wcount
wcount = a + wcount
print(ccount)
for _ in range(int(input())):
n,c,m = input().spli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.