text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author: Payne Zheng <zzuai520@live.com>
# Date: 2019/5/13
# Location: DongGuang
# Desc: 模拟range生成器
def range2(number):
count = 0
while count < number:
print("before:", count)
sign = yield count
# 只有一个函数里面有yield,那么这个函数就是个生成器
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author: Payne Zheng <zzuai520@live.com>
# Date: 2019/10/30
# Location: DongGuang
# Desc: do the right thing
"""
顺序查找:
也叫线性查找,从列表第一个元素开始,顺序进行搜索,
直到找到元素或搜索到列表最后一个元素为止
时间复杂度:
将列表从头到尾只走了一遍,为 n,时间复杂度为:O(n)
"""
def linear_search(li, val):
for idx,... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author: Payne Zheng <zzuai520@live.com>
# Date: 2019/6/3
# Location: DongGuang
# Desc: do the right thing
"""
练习1: 编写一个学生类,产生一堆学生对象
要求:
有一个计数器(属性), 统计总共实例了多少个对象
"""
class Student:
school = 'Luffycity' # 类的数据属性,所有对象都能访问(通过各对象来访问可以发现,各对象访问数据属性的内存地址是一... |
"""Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order."""
class Solution:
def twoSum(self, nums... |
cashvalue = 0
taxpayment = 0
cashvalue = int(input('Welcome to Lottery Daydream! Enter the Cash Option value of the upcoming lottery:'))
def bracketone():
global taxpayment
taxpayment = (cashvalue) * .1
def brackettwo():
global taxpayment
taxpayment = (995 + ((cashvalue-9950)*.12))
def bracketthre... |
#!/usr/bin/env python3
x = 4
#this is a comment, python automatically adds a line and a space
print('x =', x, sep = '', end = '')
print('Hello World')
print("3 / 4 = ", int(3/4))
'''
this is another comment
** is exponenet
% is still modulus
casting is done backwards
'''
print("enter a number:")
x = in... |
class Node(object):
def __init__(self, val):
self.left = None
self.right = None
self.parent = None
self.value = val
class Tree(object):
def __init__(self):
self.root = None
def add(self, node):
if self.root is None:
self.root = node
else... |
# This programme returns the numbers that
# first number is greater than last number
count = 0
for i in range(1000,10000):
if (int(str(i)[0])) > (int(str(i)[-1])): # First we convert 2 str
print(i) # 2 reach first digit
count += 1 ... |
# did u just click a file called lasagna.py? Lmao anyway... enjoy lasagna
# SRC: https://exercism.org/tracks/python/exercises/guidos-gorgeous-lasagna
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 40
def bake_time_remaining(elapsed_bake_time):
"""
Returns remaining bake time
This function takes one arg... |
import math
def merge_sort(arr):
if len(arr) >= 2:
hlen = math.floor(len(arr) / 2)
sarr_l = merge_sort(arr[:hlen])
sarr_r = merge_sort(arr[hlen:])
marr = merge(sarr_l[0], sarr_r[0])
return marr[0], sarr_l[1] + sarr_r[1] + marr[1]
else:
return arr, 0
... |
def status_bmi(bmi):
if bmi < 18.5:
print("Estas Bajo Peso")
elif bmi > 18.5 and bmi < 25:
print("Tienes Peso Normal")
elif bmi > 25 and bmi < 30:
print("Estas Sobre Peso")
else:
print("Tienes Obesidad")
def calculate_bmi(height, weight):
result = weight / (height... |
def calculate(num1, num2):
return num1 + num2
def run():
two_digit_number = input("Type a two digit number: ")
first_digit = int(two_digit_number[0])
second_digit = int(two_digit_number[1])
result = calculate(first_digit, second_digit)
print(f"{first_digit} + {second_digit} = {result}")
i... |
import math
def run():
student_heights = [156, 178, 165, 171, 187]
total_heights = 0
for height_student in student_heights:
total_heights += height_student
total_heights /= len(student_heights)
total_heights = round(total_heights)
print(total_heights)
if __name__ == "__main__":... |
def run():
bill = 0
pizzas_bill = {
"S": 15,
"M":20,
"L":25
}
pepperoni_bill = {
"S": 2,
"M": 3,
"L": 3
}
extra_cheese_bill = 1
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L : ")
... |
import time
def binary_search(list, item):
low = 0
high = len(list)
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
... |
# -*- coding: utf-8 -*-
import random as rng
"""
Program simulating walking home in one dimention
"""
__author__ = 'Marius Kristiansen'
__email__ = 'mariukri@nmbu.no'
class Walk(object):
def __init__(self, home, start=0):
"""
Constructor
- The "start" parameter can be altered, but will... |
# -*- coding: utf-8 -*-
"""
source: INF200_H15_L04 lecture. H.E.Plesser
"""
__author__ = 'Marius Kristiansen'
__email__ = 'mariukri@nmbu.no'
def median(data):
"""
Returns median of data.
:param data: An iterable of containing numbers
:return: Median of data
"""
if data == []:
raise V... |
# -*- coding: utf-8 -*-
"""
Expanding list comprehension into a conventional "for loop" -form
"""
__author__ = 'Marius Kristiansen'
__email__ = 'mariukri@nmbu.no'
def squares_by_comp(number):
return [k**2 for k in range(number) if k % 3 == 1]
def squares_by_loop(n):
squares = []
for number in range(n)... |
def add(x, y):
return x + y
def main():
x = 5
y = 2
print(add(5, 2))
if __name__ == '__main__':
main()
|
class Car:
def __init__(self, make, year, model):
self.make = make
self.year = year
self.model = model
def display_features(self):
print("Make:" + self.make)
print("Year:" + str(self.year))
print("Model:" + self.model)
class ElectricCar(Car):
def __init__(se... |
# ===> Pet class
# Task #1
class Pet(object):
def __init__(self,name,species,food_cost,noise):
self.name=name
self.species=species
self.food_cost=food_cost
self.noise=noise
# Task #2
def Speak(self):
print(self.noise)
# Task #3
def sumFoodCost(self):
sum=0
... |
x1=[1,2,1,2,]
x2=[1,2,2,1]
x3=[1,2,1,2]
def List_prop(q):
i=0
temp=0
max1=0
max2=0
min1=0
flag=''
for n in q:
if i==0:
temp=n
i=i+1
else :
if temp<n:
temp=n
i=i+1
if flag[-3:]!="max":
flag=flag+"max"
if flag.find("maxmin"):
max1=n
else:
max2=n
if temp>n:
tem... |
class Slide:
"""
Combination of images represented as a slide
List of attributes:
- photos:list = list of photos the second being None if is a horizontal pic
- is_vertical:bool = True if the slide is composed by two vertical images
- tags:set = set being the union of both set of images
... |
"""
Definition for a multi tree node.
class MultiTreeNode(object):
def __init__(self, x):
self.val = x
children = [] # children is a list of MultiTreeNode
"""
class Solution:
# @param {MultiTreeNode} root the root of k-ary tree
# @return {int} the length of the longest consecutive sequence... |
# https://www.lintcode.com/problem/sort-colors/description?_from=ladder&&fromId=1
# 1. partition x 2: partition 0 + partition 1
class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def sortColors(self, nums):
index = self.partition(nums, 0, 0, len(nums... |
from collections import Counter
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
jewelRef = set(J)
jewelCount = 0
# option A
# for stone in S:
# if stone in j... |
import re
import time
def main():
operation = ""
while operation != "q":
operation = input("Please insert your calculation or q to exit: ")
values = process(operation)
if operation == "q":
break
if len(values) < 2 or len(values) > 3:
print("ERRO... |
import sys
def fac(a):
fact=1
for i in range (1,a+1):
fact=fact*i
return fact
t=int(input())
for i in range(0,t):
n=int(input())
print(fac(n)) |
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
self.length = 0
def append_to_tail_node(self, data):
curr = self.head
new = Node(data)
while curr.next is not None:
... |
"""
Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.
Example 1:
Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Ex... |
# Definition for a binary tree node.
"""
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = ... |
# 1, 1, 2, 3, 5, 8, 13, 21, ...
def fibo_iterativo(n):
if n <= 2:
return 1
else:
t1 = 1
t2 = 1
contador = 3
while contador <= n:
t1, t2 = t2, t1 + t2
contador += 1
return t2
def fibo_recursivo(n):
if n <= 2:
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
# Everythong else is the same as singly linked lists.
# Doubly linked lists are used as to implement the Collections.deque (pronounced: deck) which helps it insert or delete an elements from both en... |
from Tkinter import *
#from PIL import Image, ImageTk
import ttk
import random
import time
window = Tk()
canvas = Canvas(window, width=854, height=480, bg="#3796da")
canvas.pack()
intPlay = 0
#Creates window and centers to any screen
window.geometry('{}x{}'. format(1060, 670)) #Setting size of window
window.withdraw... |
#Aim : Program to find the hypotenuse of a right angled triangle, when the base and height are entered by the user.
#Developer: Rakesh yadav
h = float (input("Enter height of triangle : "))
b = float (input("Enter base of triangle : "))
# calculation
hypotenuse = ((h**2) + (b**2))**0.5
print("Hypotenuse of a rig... |
# author: Rakesh yadav
# aim: Print even numbers upto 100, without using any arithmetic or comparison operator.
l = list(map(int,range(100+1)))
num_list = l[0::2]
print(num_list)
|
'''
Author : Rakesh Yadav
Aim: Use of Zip function in pyhton.
'''
a = int(input("Number of students"))
marks_in_bme = []
name = []
for i in range(a):
h = input("Enter name of students")
name.append(h)
i = int(input("Enter marks"))
marks_in_bme.append(i)
print(name)
print(marks_in_bme)
result=zip... |
#Aim : Program to find the area and perimeter of a rectangle, when the required input (Length and Breadth) are entered by the user.
#Developer: Rakesh yadav
x = float (input("Enter length of rectangle : "))
y = float (input("Enter width of rectangle : "))
# calculation
area = (x * y)
perime... |
'''
Author : Rakesh Yadav
Task: To kame a program in which
1. take an input as string from user
2. check the string if it contains all vowels or not
3. print if it satisfy above conditions.
'''
STR = input()
if ('a' or 'A' and 'i' or 'I' and 'u' or 'U' and 'o' or 'O' and 'e' or 'E') in STR :
print(STR)
|
class Rational:
'''
Rational class
'''
def __init__(self, a, b = 1):
'''
:param a: numerator
:param b: denominator
'''
assert b !=0
assert isinstance(a, int)
assert isinstance(b, int)
self._a = a
self._b = b
... |
def get_trapped_water(seq):
'''
:param seq: input list
:return: how many units of water remain trapped between the walls in the map
'''
assert isinstance(seq, list)
assert len(seq) != 0
for i in seq:
assert isinstance(i,int)
assert i >=0
n = len(seq)
left, ... |
def slide_window(x,width,increment):
'''
Implement a sliding window for an arbitrary input list
:param x: input list
:param width: window width
:param increment: window increment
:return: res
'''
assert isinstance(x, list)
assert isinstance(width, int)
assert isinstanc... |
#This is the program for a brute force approach to solving the closest points problem, and will run in O(n^2) time.
import sys
import math
import time
def writefile(points, distance):
f1 = "output_bruteforce.txt"
with open(f1, "a+") as f:
f.write(str(distance) + '\n')
for i in points:
f.write(i[0] + " " + i[... |
def num_tests():
return int(input("Enter number of assignments you've had: "))
return int(input("Enter number of tests: "))
def get_score():
score = []
test = num_tests()
for i in range(0, test):
score.append(float(input("Enter assignment grade: ")))
return score
def main():
score = get_score()
total = sum(s... |
i = 0
l = [1,2,3,4,5,6]
for ll in l:
print(ll, i)
i += 1
l.insert(1, 9)
print(l) |
class Queue:
def __init__(self):
self.queue = []
# Add an element
def enqueue(self, item):
self.queue.append(item)
# Remove an element
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
# Display the queue
def disp... |
wh =raw_input()
if(wh=='a' or wh=='e' or wh=='i' or wh=='o'or wh=='u'):
print "vowels"
else:
print "consonant"
|
from random import randint
n = 3
arr = []
for i in range(n):
sign = randint(0, 1)
if sign == 1:
arr += [['+', randint(1, 5)]]
else:
arr += [['-']]
print(n)
for x in arr:
print(*x)
|
#!/python3
# -*- coding: utf-8 -*-
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
class Fraction:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.top = int(numerator / g)
self.bottom = int(denominator / g)
def __eq__(self, other):
f... |
# Q5 Write a Python program to create and display all combinations of letters,
# selecting each letter from a different key in a dictionary
# Sample data : {'1':['a','b'], '2':['c','d']}
# Expected Output: ac ad bc bd
from itertools import product
data ={'1':['a','b'], '2':['c','d']}
print (data)
for x ... |
def decorator(cls):
print(">>>AAA 这里可以写被装饰类新增的功能")
return cls
@decorator
class A(object):
def __init__(self):
pass
def test(self):
print("test")
def decoratorB(cls):
print(">>>BBB 这里可以写被装饰类新增的功能")
class B_new(cls):
def __init__(self):
print("B_new")
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
dict1 = {}
dict1["a"] = []
dict1["a"].append(1)
dict1["a"].append(2)
dict1["n"]=2
list1 = dict1["a"]
n = dict1["n"]
dict1["a"].pop(0)
dict1["n"] -= 1
print(dict1.keys())
print(dict1["a"],list1,dict1["n"],n)
list1[0] = 10
print(dict1["a"],list1)
def getdict():
dict1 =... |
# 创建一个多线程编程的例子
import threading
def print_numbers(num):
for i in range(1, num):
print(i)
def print_letters(str):
for letter in str*10:
print(letter)
# 创建两个线程
t1 = threading.Thread(target=print_numbers,args=(100,))
t2 = threading.Thread(target=print_letters, args=("abcdefghij",))
# 启动线程
t1.st... |
from PIL import Image, ImageFilter
import cv2
def crop_edges_PIL():
# Open the image
img = Image.open("image.bmp")
# Convert the image to grayscale
img_gray = img.convert("L")
# Get the edges of the image
edges = img_gray.filter(ImageFilter.FIND_EDGES)
# Crop the image to remove the bla... |
import torch
from torch.utils.data import Dataset
class MyDataset(Dataset):
def __init__(self, data):
self.data = data
def __getitem__(self, index):
x = self.data[index][0]
y = self.data[index][1]
return x, y
def __len__(self):
return len(self.data)
# 数据
data = [(... |
Username = input("What is your Username? ")
if Username == "Homer":
password = input("password: ")
if password == "8166":
print("Successful")
else:
print("try again")
else:
print("try again")
|
def show_activity():
print()
print("1. Praca siedząca, brak dodatkowej aktywności fizycznej.")
print("2. Praca niefizyczna, mało aktywny tryb życia")
print("3. Lekka praca fizyczna, regularne ćwiczenia 3-4 razy (ok. 5h) w tygodniu")
print("4. Praca fizyczna, regularne ćwiczenia od 5razy (ok. 7h) w... |
import sqlite3
conn = sqlite3.connect('blog.db')
cur = conn.cursor()
query_del = '''delete from blogpost where id=4;'''
cur.execute(query_del)
query = '''select * from blogpost;'''
cur.execute(query)
rows = cur.fetchall()
for row in rows:
print(row)
|
import math
import graphics
import controller
import art_int
"""
letters = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9}
inv_letters = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J'}
allowed_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
... |
# coding=utf-8
'''
冒泡排序(升序)【稳定排序】
原理:
1、从第一个元素开始,开始依次对相邻的两个元素进行比较,当后面的元素大于前面的元素时,交换二者位置;
2、进行一轮比较之后,最大的元素将在序列尾部(最后一位);
3、然后对(n-1)个元素再进行第二轮比较,最大元素将在序列倒数第二位;
4、重复该过程,直至只剩下最后一个元素为止,最后的元素就是最小值,排在序列首位
以 list = [5, 4, 2, 1, 3] 为例:
第一轮排序: [4, 2, 1, 3, 5]
第二轮排序: [2, 1, 3, 4, 5]
第三轮排序: [... |
# coding=utf-8
'''
插入排序(升序)【稳定排序】
原理:
1、假设初始时假设第一个记录,自成一个有序序列,其余的记录为无序序列;
2、从第二个记录开始,按记录大小,依次插入之前的有序序列中;
3、直到最后一个记录插入到有序序列中为止
以 list = [5, 4, 2, 1, 3] 为例:
第一步,插入5之后: [5], 4, 2, 1, 3
第二步,插入4之后: [4, 5], 2, 1, 3
第三步,插入2之后: [2, 4, 5], 1, 3
第四步,插入1之后: [1, 2, 4, 5], 3
第五步,插入3之后: [1, 2, 3, 4, 5]
时间复杂度: O(n) ~ O(n**2) 平均: O... |
def readInput( file, type ):
input_file = open(file, "r")
# row delimitered list of strings
if ( type == "text_list" ):
output = []
for row in input_file :
output.append(str(row))
# Return Output
return output
if __name__ == "__main__":
# Read input
string_list = readInput("2.txt", "text_li... |
# look at basic_01.py. if you want to print a schedule of 30 days, you should think of for loop on days
members = ['Mom', 'Dad', 'Hanhan', 'Menmen']
tasks = ['Washes Dish', 'Cleans Floor', 'Cleans Table', 'Others Stuff']
for day in range (0, 30):
print 'Day', day+1, ':'
print '\t', members[0], tasks[0] # \t... |
# plus
a = 3.2
b = 5.8
c = a+b
print c
# minus
a = 3.2
b = 5.8
c = a-b
print c
# times
a = 3.2
b = 5.8
c = a*b
print c
# divide
a = 3.2
b = 5.8
c = a/b
print c
#remainder (integer only)
a=187
b=13
print a%b
#power
a=2.0
b=3
print a**b
#task, write some math expression on paper, translate them to python. |
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a list of strings
def wordBreak(self, s, dict):
n = len(s)
A = [None] * n
i = n-1
while i >= 0:
if s[i:n] in dict:
A[i] = [n] # A[i] contains "n" means s[i..n-1] is ... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
list = []
stack = []
... |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# table = {}
# for i in s:
# if i in table:
# table[i] += 1
# else:
# table[i] = 1
# for i in t:
# if i in ... |
#Bubble Sort
def bubbleSort(items):
for i in range(len(items)):
for j in range(len(items) - i - 1):
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j]
#Insertion Sort
def insertionSort(items):
for i in range(1, len(items)):
j = i
while j > 0 and items[j-1] > items[j]:
items[j], ite... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap = []
for node... |
# https://www.codewars.com/kata/does-my-number-look-big-in-this/
def narcissistic(n):
# return value == sum(int(x) ** len(str(value)) for x in str(value))
"""
A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number
of digits.
For example, tak... |
# https://www.codewars.com/kata/snail
# Не уложился по времени :)
def snail(a):
"""
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling
clockwise.
array = [[1,2,3],
[4,5,6],
[ 7,8,9]]
snail(array) #=> [1,2,3,6,9,8... |
# https://www.codewars.com/kata/which-are-in/
# Не прошёл тесты. Не могу понять почему
def in_array(a1, a2):
d = {}
for x in sorted(a1):
d[x] = 0
for y in a2:
if x in y:
d[x] += 1
res = []
for x in d:
if d[x] > 0:
res.append(x)
retur... |
from data import *
def solve():
floor = 0
position = 1
final_position = 0
for paren in parens:
if paren == "(":
floor = floor + 1
else:
floor = floor - 1
if floor == -1 and final_position == 0:
final_position = position
position = posi... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class CircularDoublyLinkedList:
def __init__(self):
self.first = None
def get_node(self, index):
current = self.first
for i in range(index):
current = curre... |
a=[1,2,4,5]
print a
b=[1,2,3,4]
c=a+b
print c
for i in c:
print i
print 3 in a #search
a=[2,3,1,4]
a.append[5]
print a |
n= input('Enter a number:')
sum = 0
i=n
temp=n
while(i>0):
Factorial = 1
i = 1
Reminder = Temp % 10
while(i <= Reminder):
Factorial = Factorial * i
i = i + 1
print("\n Factorial of %d = %d" %(Reminder, Factorial))
Sum = Sum + Factorial
Temp = Temp%10
print("\n Sum of Fact... |
import re
x='virat is good boy'
if(re.search('Good',x,re.I)): #I:Ignore case
print "Found"
else:
print "Not Found" |
def fun(x,y):
z=x+y
return z
a=fun(10,20)
print a
def factorial(num):
f=1
for i in range(1,num+1):
f=f*i
return f
n=input('Enter a number')
result=factorial(n)
print result |
add = lambda x,y:x+y
print add(20,30)
cube = lambda x: x ** 3
print cube(4)
joinStr = lambda *args: "-".join(args)
print joinStr("Hi", "Hello")
print "Passing a function name as a parameter in a function"
def doOperations(operation,a,b):
print operation(a,b)
def subtract(a,b):
print a-b
doO... |
adharDB = {}
#input from user
# His adhar number, Name of the person, mobile number and city
# save it in your dict
# Enter for three records
# Key adar num
# value is dictionary containing : key personName, key mobile value = number and Key city and value
# value {'name': , 'mobile':, 'city':}
for _ in r... |
import re
str1 = "john 1234 12/12/2000 , merry 893 01-02-1994 2333 1/1/98"
#DOB
print "Get on DOB =",re.findall(r'\d+[/-]\d{1,2}[/-]\d{2,4}',str1)
#only year of birth
print "Get on Year Of birth =",re.findall(r'\d+[/-]\d{1,2}[/-](\d{2,4})',str1)
str2 = "12.23.10.1 127.0.0.1 23.34 100.1.11"
print "Valid I... |
"""
----------------
Client Server
----------------
Create a TCP/IP side using socket() function
Connect the socket with the host name and port of the server using connect method
Send /receive the message to the client using send() and recv()
Disconn by closing the socket using close()
"""
# Here we are crea... |
# Required arguments : These are mandatory. The user must provide them when calling the function else error. Order of calling the argument should be followed as the func definition
# Keyword arguments : Here we provide the parameter name and the value, the order of the parameter can be anything
# Default arguments : ... |
class Parent1(object):
def displayInfo(self):
print "Parent 1"
# end of Paren1 class
class Parent2(object):
def displayInfo(self):
print "Parent 2"
# end of Paren2 class
class Child(Parent1, Parent2):
def displayInfo(self):
super(Child, self).displayInfo()
# ... |
"""Lists Example
Append, extend, insert, remove del """
data = ['c', 'c++', 'Java', 100, 200]
#Operations
print "Number of elements in my list = ", len(data)
print "First element: ", data[0]
print "Last element: ", data[-1]
#Member ship
print "Is python in mylist = ", 'python' in data
print "Is Java in myl... |
# Brute force solution
import time
import math
start = time.time()
def largest_prime_factor(num):
highest_prime = 2
for i in range(2, num + 1):
while num % i == 0:
# print(num, 'num')
highest_prime = i
num /= i
# print(num, 'num')
return highest_prime
... |
# sorted.py
# More on the sorted function
# Sort the words from a sentence
sentence = "I like turtles, especially purple ones"
# Notice words aren't sorted correctly!
print(sorted(sentence.split()))
# Now they are
# Note the key= at the end
print(sorted(sentence.split(), key=str.upper))
|
# demo of creating a list of grades
# getting lowest and highest scores from it
# create list to hold grades
grades = []
# add 5 grades to the list
for i in range(5):
# get input as string
grade = input("Grade? ")
# append to list and force to float
grades.append(float(grade))
# sort the grades
grade... |
theSentence = 'Bruce prefers teaching in a classroom rather than online'
# break apart the words in the sentence into a list using .split()
theSentence = theSentence.split()
print('Here are the words in the sentence:',theSentence)
# example data in the form of a string where each name is separated by a comma
someDat... |
'''
Author: M. Canesche
Date: 01/12/18
About: Speech Recognition for text just in english.
'''
# libraries
import speech_recognition as sr
def main():
r = sr.Recognizer() # initialize recognizer
with sr.Microphone(device_index=0) as src:
print("Speak Anything: ")
au... |
#GC26
import random
import string
def randomString(stringLength):
letters = string.ascii_letters
return ''.join(random.choice(letters) for x in range(stringLength))
newword = randomString(8)
print("Please type in",newword)
typeword = input(":")
if newword == typeword:
print("Success")
else:
print("Fail... |
# -*- coding:utf-8 -*-
import random
# 元组推导式 快速生成一个元组
# 与列表推导式不同 元组推导式生成的结果是一个生成器对象 需要强制转换(tuple()和list())来生成元组或列表
# 生成器对象在执行tuple()或者list()函数后就会被清空
random_number = (random.randint(10, 20) for x in range(10))
print("生成的生成器对象为:", random_number)
random_number1 = (random.randint(10, 20) for i in range(10))
# 强制转型
... |
# -*- coding:utf-8 -*-
from Shape import Shape
class Square(Shape):
def __init__(self, side):
Shape.__init__(self, side, side)
self.side = side
def area(self):
print("矩形的面积为:", self.side**2)
def girth(self):
print("矩形的周长为:", self.side*4)
|
# -*- coding: utf-8 -*-
# 序列的定义和下标的读取
list = ["哇哈哈哈哈哈","ohohohohh00","nnnnnnnnnnnnnnnnn"]
# python中允许下标为副,下标-1为数组最后一个元素
print(list[2])
print(list[-1])
# 序列的切片操作
# sname(start:end:step)i
# sname : 名字 start: 切片操作开始的位置 end:切片操作结束的位置
print("将数组切片输出的结果是:")
print(list[1:2])
# 序列相加,生成新的序列
list1 = ["我日"]
lis... |
import os
list1=[]
list2=[]
for (a,b,c) in os.walk('D:\\'):
if c!=[]:
list1.append(c)
if b!=[]:
list2.append(b)
print(list1)
print(list2) |
#board = [[3, 0, 6, 5, 0, 8, 4, 0, 0],
# [5, 2, 0, 0, 0, 0, 0, 0, 0],
# [0, 8, 7, 0, 0, 0, 0, 3, 1],
# [0, 0, 3, 0, 1, 0, 0, 8, 0],
# [9, 0, 0, 8, 6, 3, 0, 0, 5],
# [0, 5, 0, 0, 9, 0, 6, 0, 0],
# [1, 3, 0, 0, 0, 0, 2, 5, 0],
# [0, 0, 0, 0, 0, 0, 0, 7, 4],
# ... |
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
menu = Menu()
coffee_machine = CoffeeMaker()
register = MoneyMachine()
machine_is_on = True
# put everything in a while loop
while machine_is_on:
# Get user's choice
choice = input(f"What would you like... |
# 리스트list
odd=[1,2,3,4,5,6]
print(type(odd))
odd1=[1,3,"문자",[3,4,5]]
print(odd1[3][0])
#리스트 인덱싱, 슬라이싱
# a= [1,2,3]
#list의 a의 첫번쨰 값
#a[0]
#b = a[0] + a[2]
#print(b)
#print(a[-2])
a = "HEELO"
print(a[0:3])
a= [1,2,3,4,[1,2,3]]
print(a[-1][1:])
#리스트 연산(더하기, 곱하기, 길이구하기)
b=[1,2,12,13,14,15]
print(a+b)
print(b*3)
b1 = ... |
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randint(0,10, (4,2)), index = ["A", "B", "C", "D"],
columns=["a", "b"])
print(df1)
print()
df2 = pd.DataFrame({"a":[1,2,3,4], "b":[5,6,7,8]}, index = ["A", "B", "C", "D"])
print(df2)
arr = np.array([("item1", 1), ("item2", 2), (... |
# coding=utf-8
# author:MagiRui
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('2018/12/18',
periods=10), columns=list('ABCD')) # 数据 索引 列
print(df)
ds = df.plot() # 折线图
plt.show() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.