text stringlengths 37 1.41M |
|---|
square = {f"Square of {num} is" : num**2 for num in range(1, 11)}
for k, v in square.items():
print(f"{k} : {v}")
string = "Neeraj"
count = {char : string.count(char) for char in string}
print(count) |
from functools import wraps
import time
def calc_time(func):
@wraps(func)
def wrapper_func(*args, **kwargs):
print(f"executing {func.__name__} function")
t1 = time.time()
ret = func(*args, **kwargs)
t2 = time.time()
print(f"time taken is {t2 - t1}")
return ret
... |
class Phone:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = max(price, 0)
def name(self):
return f"{self.brand} {self.model}"
def make_call(self, mob_num):
return f"calling {mob_num}"
class Smartphone(Phone):
def __ini... |
with open("file.txt", "w") as f:
f.write("hello\n")
with open("file.txt", "a") as f:
f.write("I'm Neeraj\n")
with open("file.txt", "r+") as f:
f.seek(len(f.read()))
f.write("\nI'm a student") |
numbers = list(range(1, 11))
print(numbers)
popped = numbers.pop()
print(popped)
print(numbers)
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 5, 8, 3, 9, 5]
print(num.index(3, 10, 14))
def negative_list(l):
neg_num = []
for i in l:
neg_num.append(-i)
return neg_num
print(negative_list(num)) |
def greater(a, b):
if a > b:
return a
return b
num1 = int(input("Enter first number : "))
num2 = int(input("Enter second number : "))
g = greater(num1, num2)
print(f"{g} is greater") |
# @author
# Aakash Verma
# www.aboutaakash.in
# www.innoskrit.in
# Instagram: https://www.instagram.com/aakashverma1102/
# LinkedIn: https://www.linkedin.com/in/aakashverma1124/
# Youtube: https://www.youtube.com/channel/UC7A5AUQ7sZTJ7A1r8J9hw9A
# Problem Statement: Given a string, sort it in decreasing order based o... |
'''
Created on 2017-06-28
@author: jack
'''
import matplotlib.pyplot as plt
plt.plot([1,2,5,9,3])
plt.title('plot a line')
plt.show() |
# coding=utf-8
"""
Given a DNA sequence, give the most divergent sequence that produces the same polypeptide
Usage:
decodon.py INPUT [--N=1]
Arguments:
INPUT The input sequence
Options:
-h --help Show this screen.
--N=<int> [default: 1] The number of degenerate sequences to print
Output:
Degenerate DN... |
## Python Crash Course
# Exercise 4.12: Buffet:
# A buffet-style restaurant offers only five basic foods. Think of five simple foods, and store them in a tuple.
# • Use a for loop to print each food the restaurant offers.
# • Try to modify one of the items, and make... |
## Python Crash Course
# Exercise 8.6: City Names:
# Write a function called city_country() that takes in the name of a city and its country.
# The function should return a string formatted like this: "Santiago, Chile"
# Call your function with at least three city-country p... |
## Python Crash Course
# Exercise 4.6: Odd Numbers:
# Use the third argument of the range() function to make a list of the odd numbers from 1 to 20.
# Use a for loop to print each number.
def main():
# Prepare list of odd numbers in 1 to 20
listOfOddNumbers = list(range(1,21,... |
## Python Crash Course
# Exercise 2.5: Famous Quote:
# Find a quote from a famous person you admire. Print the
# quote and the name of its author. Your output should look something like the
# following, including the quotation marks:
# Albert Einstein once said,... |
## Python Crash Course
# Exercise 3.7: Shrinking Guest List:
# You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests.
# • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you ca... |
## Python Crash Course
# Exercise 4.2: Animals:
# Think of at least three different animals that have a common characteristic.
# Store the names of these animals in a list, and then use a for loop to print out the name of each animal.
# • Modify your program to print a sta... |
print("Yo! Вводите числа пока не устанете! Когда закончите наберите слово stop")
list = []
stopword = 0
i = 0
buf = 0
while stopword != 1:
list.append(input("\n"))
print("Вы ввели: ",list[i], "номер шага", i)
if list[i] == "stop":
stopword = 1
list.remove("stop")
else:
i = i + 1
... |
# Write a program that creates a list of tuples for all the numbers in a given limit and
# indicate whether number is Prime or Non Prime.
def fun(n):
ans = {}
for integer in range(1,n+1):
if (prime(integer)):
ans[integer] = "Prime"
else:
ans[integer] = "Non Prime"
print (ans)
def... |
# Write a Python function that takes a list and returns a new list with unique
# elements of the first list
def uniqueList(list):
unique_list = []
for i in list:
if i not in unique_list:
unique_list.append(i)
return unique_list
list = []
num = int(input("Enter the number of elem... |
import math
class Angle:
def __init__(self, value, unit='deg'):
if unit == 'deg':
self._value = math.radians(value)
elif unit == 'rad':
self._value = value
else:
raise ValueError(f'{unit} is not recognized')
def __call__(self, unit='rad'):
i... |
# Author: Efrain Noa
# email: enoay7@yahoo.com; noayarae@oregonstate.edu
# Programacion Orientada a objetos
# Creacion de Herencias - superclases
# Code developed based on video 31 "curso python" from https://www.youtube.com/watch?v=oe04X1B14YY&list=PLU8oAlHdN5BlvPxziopYZRd55pdqFwkeS&index=31
class persona():
def... |
class Fraction:
def __init__(self,top=0,bottom=1):
#denominator can not be zero
if bottom==0:
raise ZeroDivisionError("Den. can not be zero")
if top == 0:
self.num = 0
self.den = 1
else:
#Determine regarding the sign of the nu... |
#Guess the Number
import random;
rn = random.randint(1,3)
#print (rn)
Try=0
while(Try<3):
userguess = input('Guess the number between 1 and 3');
print(userguess);
if (rn==userguess):
print("CONGRATS");
else:
print("Try Again");
Try = Try + 1;
|
def parse_functions(input_string):
try:
if input_string.find(",") == -1 and input_string.find("(") == -1:
return [input_string]
else:
# We need to separate the commas from 1, 3, add(1, 3), 2, add(3), but no the ones inside parenthesis!!
new_string = input_string.replace(" ", "") #get rid of ... |
from __future__ import division
import math
"""
This is the code file for Assignment from 23rd August 2017.
This is due on 30th August 2017.
"""
##################################################
#Complete the functions as specified by docstrings
# 1
def entries_less_than_ten(L):
"""
Return those elements o... |
# Charla
print("Inicia conversacion\n")
while 1:
a = raw_input()
if a == "hola":
print("Que tal?\n")
elif a == "chao":
print("Chau\n")
exit()
else:
print("Que?\n")
|
# -*- coding: utf-8 -*-
#A matrix is a rectangular table of values divided into rows and columns. An m×n matrix has m rows and n columns. Given a matrix A, we write Ai,j to indicate the value found at the intersection of row i and column j.
#
#Say that we have a collection of DNA strings, all having the same length n. ... |
def quick_sort(data):
less = []
equal = []
greater = []
if len(data) > 1:
pivot = data[0]
for i in data:
if i < pivot:
less.append(i)
if i == pivot:
equal.append(i)
if i > pivot:
greater.append(i)
... |
from math import radians
class Vehicle:
def __init__(self, id, lat, long):
self.id = id
self.lat = radians(lat)
self.long = radians(long)
self.rawLat =lat
self.rawLong = long
def show(vehicle):
print("Vehicle %d - location [%f,%f]" %(vehicle.id,vehicle.rawLat,vehicle.rawLong))
# Ra'an... |
>>> import time
>>> epoch = time.time()
>>> total_sec = epoch %86400
>>> hours = int(total_sec/3600)
>>> total_min = int(total_sec/60)
>>> mins = total_min % 60
>>> sec = int(total_sec %60)
>>> days = int (epoch/86400)
>>>
>>> print("Number of days since the epoch:", days,",", "Current time:", hours,"hours",... |
"""Checks the validity of filepaths with reagards to their chosen import destination."""
import os
def CheckPcaValid(fileName):
"""Checks if its a valid PCA file. """
namelist = fileName.split('.')
valid= False
for i in range(0,len(namelist)):
if(namelist[i] == 'pca'):
valid =... |
List1 = []
List1.append(1)
List1.append(2)
List1.append(3)
List1.append(4)
List1.append(5)
print "Before Reverse "
for x in List1 :
print x
List1.reverse()
print "After Reverse "
for x in List1 :
print x
cOutput = raw_input()
|
List1 = []
List1.append(2)
List1.append(1)
List1.append(4)
List1.append(9)
List1.append(3)
List1.append(8)
List1.append(7)
print "Before sort "
for x in List1 :
print x
List1.sort()
print "After Sort "
for x in List1 :
print x
cOutput = raw_input()
|
# Code to connect the NodeMCU (ESP8266) to a WiFi network.
import network # The network module is used to configure the WiFi connection.
sta_if = network.WLAN(network.STA_IF) # Station interface.
ap_if = network.WLAN(network.AP_IF) # Access point interface.
# Checking if interfaces are active.
"""
Upon ... |
# Write a Python program to find the largest and smallest number in an unsorted array.
array=[int(x) for x in input().split()]
n=len(array)
big=small=array[0]
for i in range(1,n):
if (array[i]>big):
big=array[i]
if (array[i]<small):
small=array[i]
print("Largest value =", big)
print(... |
from turtle import Turtle
ALIGN = "center"
FONT = ("Arial", 16, "normal")
class Scoreboard(Turtle):
def __init__(self):
"""create the score board display"""
super().__init__()
self.score = 0
self.color("white")
self.penup()
self.hideturtle()
sel... |
from os import close
from Parameter import *
'''
enemy 寻路模块
'''
class Point_direction:
def __init__(self,position:tuple,father_position:tuple,mht_distance) -> None:
self.position = position
self.father_position = father_position
self.mht_distance = mht_distance
'''Greed-Bes... |
# Global variable to hold all the colorus for the rainbow
# Red Orange? Yellow Green Blue Violet
colours = ["\033[91m", "\033[33m", "\033[93m", "\033[32m", "\033[34m", "\033[35m"]
def flag():
global colours # Use the global variable colours
line = 50 * "\u2588" # Uni... |
def bubble_sort(lst):
"""Time complexity - O(N^2 - N) = O(N^2)"""
sorted = False
while not sorted:
sorted = True
for idx in range(len(lst) - 1):
if lst[idx] > lst[idx + 1]:
lst[idx], lst[idx + 1] = lst[idx + 1], lst[idx]
sorted = False
return... |
# Example of Multi-level Inheritance: Father inherits from Grandfather and Son inherits from Father. So Son has characteristics of father and grandfather.
# Base class -
class MusicalInstruments:
numberOfKeys = 12
# Following class will inherit from base class - MusicalInstruments
class StringInstruments(MusicalIn... |
# Multiple inheritance - A class can inherit attributes and methods from more than 1 base class.
# When the base class is only used to inherit attributes, then they can be initialized directly only without __init__method.
# In following example, both classes - OperatingSystem and Apple are having same variable: name.... |
import os
import numpy
def normalize_article(article_path):
"""
returns a normalized article (see below) as a single string.
"""
result_str = ""
with open(article_path, 'r') as f:
"""
open file to read
"""
for line in f:
line = line.strip()
fo... |
from scipy.stats import linregress
def linear_regression(cases, air_qualities):
'''takes a list of cases and list of air_qualities as inputs. Returns the results
of linear regression analysis performed by scipy.stats'''
return linregress(cases, air_qualities)
def check_if_entry_exists(state, city, from_d... |
import utils
import sys
import re
class Questionnaires:
def get_search_entity(self, entities):
print("Select ")
for index, key in enumerate(entities):
print(f"{index + 1}) {utils.capitalize(key)}")
choice = ''
while not re.search("^[123]$", choice):
choice ... |
import turtle
wn=turtle.Screen()
t1=turtle.Turtle()
t2=turtle.Turtle()
t2.penup()
t2.goto(100,100)
t2.pendown()
t2.fd(200)
def keyup():
t1.fd(50)
def keydown():
t1.back(50)
def keyright():
t1.right(90)
def keyleft():
t1.left(90)
def addkeys():
wn.onkey(keyup,"Up")
wn.o... |
import matplotlib
import matplotlib.pyplot as plt
def charCount(word):
d=dict()
for c in word:
if c not in d:
d[c]=1
print d
else:
d[c]=d[c]+1
print d
plt.bar(range(len(d)),d.values(), align='center')
plt.xticks(range(len(d)), list... |
name = 'Bobo Love'
age = 34
height = 76
weight = 240
eyes = 'Brown'
teeth = 'White'
hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall, or {height*2.54} centimetres.")
print(f"He's {weight} pounds heavy, {weight/2.21} kilograms.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f... |
import math
def demo_tuple():
p12 = "joe", 'gomex', 12
print(p12)
print(p12[2])
def demo_dictionary():
p12 = {"fname": "joe", "lname": "gomez", "number": 12}
print(p12)
print(p12['lname'])
class player:
pass
class player2:
def __init__(self):
self.fname = ""
self.... |
if __name__ == '__main__':
n = int(input())
cnt = 1
res = []
while cnt <= n:
res.append(cnt)
cnt = cnt + 1
cnt = 0
while cnt < n:
print(res[cnt], end = '')
cnt = cnt + 1 |
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# __author_: SHEN HONGCAI
import heapq
import math
graph = {"A": {"B": 5, "C": 1},
"B": {"A": 5, "C": 2, "D": 1},
"C": {"A": 1, "B": 2, "D": 4, "E": 8},
"D": {"B": 1, "C": 4, "E": 3, "F": 6},
"E": {"C": 8, "D": 3},
"F": {"D": 6... |
"""
@Project Name: pycharmproj
@Author: Shen Hongcai
@Time: 2019-03-19, 10:20
@Python Version: python3.6
@Coding Scheme: utf-8
@Interpreter Name: PyCharm
"""
import timeit
def selectSort(arr):
n = len(arr)
for i in range(n-1): # 需要遍历 n-1 次
for j in range(i,n):
if arr[i]>arr[j]:
... |
from typing import List, Tuple, Union
from bounding_box import BoundingBox
import math
class Coordinate:
"""
Coordinates of a point a 2D plane
Attributes
----------
x: float
x coordinate of the point
y: float
y coordinate... |
import socket #lets me use TCP sockets in
import tkinter #handles GUI
import base64
import blowfish #handles encryption
from threading import Thread # allows multi threading
from datetime import datetime # lets me get current time
cipher = blowfish.Cipher(b"thisIsATest")
# server's IP address
print("some... |
'''
After passing through the Tiles Room and getting the Cradle of Life, now Indiana
Croft faces a new challenge before being able to leave the Temple Cursed. It's found
on a bridge under which there is deep darkness. Fortunately, this place
It also appears in the diary. The bridge crosses the so-called Valley of Shado... |
'''
We have a vector V[1..N] containing unique integers, and ordered from lowest to highest.
This vector is coincident if it has at least one position equal to its value.
E.g. [-14,-6,3,6,16,28,37,43], V[3] = 3; so this vector is coincident.
Algorithm with efficiency less or equal than O(log N) that checks if coinci... |
import random
def find_smallest_duplicate_number(numbers):
# _numbers = []
# for i in sorted(numbers):
# if i not in _numbers:
# _numbers.append(i)
# else:
# return i
numbers = list(sorted(numbers))
# for i in range(len(numbers)):
# if numbers[i] == num... |
def reverse_number(number):
"""
1) Convert number to a string and trim away the zeros that are on the right
2) Convert that string into a list, and reverse it ([::-1])
3) In case the input number is negative, strip out the - sign
4) Join that list back to a string with no seperation
5) Convert b... |
def factorial(factor):
result = 1
while factor > 0:
result *= factor
factor -= 1
return result
def factorial_recursion(n):
# 5! = 5 x 4!
if n == 1:
return n
else:
return n * factorial_recursion(n - 1)
# print(factorial(5))
print(factorial_recursion(5))
|
'''
Task
Read an integer n . For all non-negative integers i<n
, print i^2 . See the sample for details.
'''
n = int(input())
for i in range(n) :
print(pow(i,2)) |
#!/usr/bin/python3
'''
Barca by Al Sweigart
A chess-variamt where each player's mice, lions, and elephants try to
occupy the watering holes near the center of the board.
Barca was invented by Andrew Caldwell http://playbarca.com
'''
import sys
# set up the constants
SQUARE_PLAYER = "Square Player"
ROUND_PLAYER = "R... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import reduce
words = [u'Я', u'помню', u'чудное', u'мгновение',
u'передо', u'мной', u'явилась', u'ты', ]
# выдать список длинн слов с помощью операции map
words_lengths = list(map(len, words))
print("Список длин слов: ", words_lengths)
# отфильтровать толь... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function # для совместимости с python 2.x.x
# Дата некоторого дня определяется тремя натуральными числами y (год), m (месяц) и d (день).
# По заданным d, m и y определите дату предыдщуего дня.
#
# Заданный год может быть високосным. Год счита... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from homework5.char_frequency_histogram_maker import CharFrequencyHistogramMaker
class CharFrequencyTest(unittest.TestCase):
def compare_histogram_and_answer(self, source_file, answer_file, min_frequency=None, max_frequency=None):
v = CharFre... |
#!/usr/bin/env python3
import sys
import time
from colors import bcolors
import colors
"""
A small program to calculate the tip amount at varying percentages
"""
class TipCalculator:
newTotal = 0
def print_instruction():
print(f'{bcolors.YELLOW}Usage : Enter the Total Bill amount and Tip % (options are 10,15,2... |
import os
try:
file = input("Masukkan Nama File : ")
if os.path.exists(file):
mode = "a"
else:
mode = "r"
isiFile = open(file, mode)
lanjut = True
while(lanjut == True):
data = input("Data yang ditambahkan : ")
isiFile.write(" " + data)
opsi ... |
#!/user/bin/python3
# fare=float(input("Température en degrès Farenheit "))
# celc=(fare-32)/1.8
# print("en degrès celcius cela fait : ", celc)
# if celc>0:
# print("ça va il ne va pas geler ")
# else:
# print("Tous aux abris il va faire très très froid")
def CONVERSION(f):
c=(f-32)/1.8
return c
|
import re, nltk, argparse
def get_score(review):
return int(re.search(r'Overall = ([1-5])', review).group(1))
def get_text(review):
return re.search(r'Text = "(.*)"', review).group(1)
def read_reviews(file_name):
"""
Dont change this function.
:param file_name:
:return:
"""
file =... |
# Если выписать все натуральные числа меньше 10, кратные 3 или 5,
# то получим 3, 5, 6 и 9. Сумма этих чисел равна 23.
# Найдите сумму всех чисел меньше 1000, кратных 3 или 5.
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find th... |
#!usr/bin/python3
"""
This file creates a script that generates a random list and then sorts the list using a bubble
sort, merge sort, and pythons built in list sort. The purpose of this is to use the cProfile
module to time the different sort functions. The results of the cProfile are included as comments
at the... |
class Empleados:
conteo = 0 #variable global modificable por cada objeto, los dos guiones bajos son para privados.
def __init__(self, nombre, salario): #Self es para usar atributos/variables de la misma clase. Por lo general TIENE que ir...
self.nombre = nombre #"""esto es el costructo... |
str1=input()
s=list(str1)
s.append('.')
s=''.join(s)
print(s)
|
cf=input()
if((ord(cf)>64 and ord(cf)<91) or (ord(cf)>96 and ord(cf)<123)):
print('Alphabet')
else:
print('No')
|
# imports
import streamlit as st
import pandas as pd
def write():
"""Used to write the page in the app.py file"""
st.title('Data description')
st.write("""
Most of the data fields are easy to understand, but just to highlight some of the features present:
*Store, Date, Sales, Customers, Open, Stat... |
# @author Huaze Shen
# @date 2020-05-05
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def reverse_list(head: ListNode) -> ListNode:
if head is None:
return head
dummy = ListNode(0)
dummy.next = head
cur = head
while cur.next is not None:
... |
# @author Huaze Shen
# @date 2020-06-25
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_sub_structure(A: TreeNode, B: TreeNode) -> bool:
return (A is not None and B is not None) and (helper(A, B) or is_sub_structure(A.left, B) or is_sub_st... |
#! /usr/bin/env python3
# https://www.hackerrank.com/challenges/power-of-large-numbers/problem
x, y = input().split()
x, y = int(x), int(y)
print(pow(x, y, (10**9 + 7))) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Apr-17-20 02:55
# @Author : Kan HUANG (kan.huang@connect.ust.hk)
from torch import nn
from torch.nn import functional as F
class LeNet5(nn.Module):
"""LeNet-5 implemented with PyTorch
LeNet5 的结构,是 conv2d x3 和 FC x2
Args:
... |
from abc import ABCMeta, abstractmethod
from observer import Observer
class Observable(metaclass=ABCMeta):
observers = []
changed = False
def add_observer(self, observer):
if isinstance(observer, Observer):
print('Add', observer, ' to observer list')
self.observers.appe... |
from abc import ABCMeta, abstractmethod
class PizzaStore(metaclass=ABCMeta):
def order_pizza(self, type):
pizza = self.create_pizza(type)
pizza.prepare()
pizza.bake()
pizza.cut()
pizza.box()
return pizza
@abstractmethod
def create_pizza(self, type)... |
item_list = []
for i in range(0,3):
a = input("Enter a number:")
item_list.append(int(a))
item_list.sort()
item_list.reverse()
for item in item_list:
print(item,end = " ")
|
"""This function accepts a number and converts it to hours and minutes
"""
def hours_and_mins(number):
hours = number // 60 # Converts number to hours
mins = number % 60 # Converts number to minutes
if hours <= 1 and mins <= 1:
time = f"{number} is {hours} hour, {mins} minute"
elif hours <= ... |
par = 'parimpar'
i = int(input('coloque um numero de telefone'))
if 1 % 2 == 0:
print("par")
else:
pŕint("impar") |
# Python program for Plotting Fibonacci
# spiral fractal using Turtle
import turtle
import math
def fibo_plot(number):
a = 0
b = 1
square_a = a
square_b = b
# Setting the colour of the plotting pen to blue
pen.pencolor("blue")
# Drawing the first square
pen.forward(b * factor)
pe... |
'''
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
main = []
for n in range(99, 999999):
if len(str(n)) == len(str(2 * n)) == len(str(... |
__author__ = 'shenyao'
def power(x,n):#位置参数
s=1
while n>0:
n=n-1
s=s*x
return s
print(power(5,2))#位置参数
print(power(5,3))#位置参数
def power(x,n=2):#默认参数(必选参数在前,默认参数在后)
s=1
while n>0:
n=n-1
s=s*x
return s
print(power(5))
print(power(5,3))
def enroll(name,gender,a... |
__author__ = 'shenyao'
class Hello(object):
def hello(self,name="world"):
print("Hello,%s" % name)
h = Hello()
print(type(Hello)) #type
print(type(h))
h.hello()
#我们说class的定义是运行时动态创建的,而创建class的方法就是type函数
def fn(self,name="world,welcome"):#先定义函数
print("Hello,%s" % name)
#type方法参数解释
#1 cl... |
'''
Created on Sep 7, 2016
@author: sheldonshen
'''
#1定制类之__str__
class Student(object):
def __init__(self,name):
self._name=name
def __str__(self):
return 'Student object (name:%s)' % (self._name)
__repr__=__str__
s = Student("simon")
print(s)
#2定制类之... |
'''
Created on Sep 7, 2016
@author: sheldonshen
'''
class Animal(object):
pass
#大类
class Mammal(Animal):
pass
class Bird(Animal):
pass
class RunnableMixIn(object):
def run(self):
print("Running....")
class FlyableMixIn(object):
def fly(self):
print("Flying..... |
'''
Created on Sep 6, 2016
@author: sheldonshen
'''
#1函数作为返回值
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
def lazy_sum(*args):
def mysum():
ax = 0
for n in args:
ax=ax+n
return ax
return mysum;
print(calc_sum(1,2,3,4))
f = lazy_sum... |
# def writetextfilesusingwith(self):
# with open(order_text, "w+") as file, open(writer_text, "w+") as file2:
# try:
# file_input = (input("Enter your file input:"))
# if len(file_input) == 0:
# raise Exception("sorry we dont take empty names")
# except Excep... |
from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
ps = PorterStemmer()
example_words = ["cats","animals","men","boys","children"]
for word in example_words:
print(ps.stem(word))
new_text = "It is important to by very pythonly while you are pythoning with python. All pyth... |
import nltk
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
sentence = "running studying eats verification friendly chatbots"
punctuations="?:!.,;"
sentence_words = nltk.word_tokenize(sentence)
for word in sentence_words:
if word in punctuations:
sentence_words.remove(word... |
temp = [1, 2, 3, 4, 5, 6]
# result = [expression,for userDefKey in itarableList]
result = [x * x for x in temp]
print(result)
# now another magic in list
temp2 = [1, 2, 3, 4, 5, 6]
result2 = [x for x in temp2 if x % 2 == 0]
print(result2)
print(type(result2) is bool)
result3 = [x for x in result2 if x % 2 == 0]
result4... |
import time
from datetime import datetime
currentDate = datetime.now()
print(currentDate)
currentDay = datetime.now().day
print(currentDay)
print(datetime.now().minute) # current minute
print(datetime.now().second) # current second
print(datetime.now().time()) # current time
# for get timeStamp
timestamp = int(ti... |
temp = 32
# if temp == 30:
# print("ok")
# else:
# print("No")
val = temp if temp == 30 else "No"
print(val)
|
# for variable and data types
name = "Golam Kibria"
age = 25
print(name, age, "Dhanmondi dhaka bangladesh")
|
#多线程-共享全局变量
#多线程之间共享全局变量有两种方式:
#子线程函数使用global关键字来调用函数外全局变量
#列表当作实参传递到线程中
#在一个进程内所有的线程共享全局变量,很方便在多个线程间共享数据
#缺点就是,线程是对全局变量随意遂改可能造成多线程之间对全局变量的混乱(即线程非安全)
# 共享全局变量-global全局变量
#例如:
# from threading import Thread
# from time import sleep
# num=100
# def work1():
# global num
# for i in range(3):
# num+=1
... |
class F(object):
__money=1
n=333
def __init__(self,name,age):
self.name=name
self.age=age
self.sex='男性'
def classid(self):
return '1809A'
@classmethod
def secret(cls):
return cls.__money
@classmethod
def change(cls):
cls.__money=10
class F... |
#发送数据
# from socket import *
# udp_socket=socket(AF_INET,SOCK_DGRAM)
# socket_data=input('请输入你要发送的数据:')
# s=('192.168.1.3',8080)
# udp_socket.sendto(socket_data.encode('gb2312'),s)
# udp_socket.close()
#发送接收数据
# from socket import *
#
# # 1. 创建udp套接字
# udp_socket = socket(AF_INET, SOCK_DGRAM)
# # 2. 准备接收方的地址
# dest_a... |
class Hero(object):
def __init__(self,name,age):
self.name=name
self.age=age
def moving(self):
print('正在赶往战场')
def attact(self):
print('大保健...')
if __name__ == '__main__': #程序入口
f = Hero('黄忠', 18)
f2 = f # 引用计数+1
f3 = f # +1
print(id(f))
print(id(f2... |
# for x in range(1001):
# for y in range(1001):
# for z in range(1001):
# if (x+y+z==1000) and x**2+y**2==z**2:
# print(x,y,z)
# 执行时间会有很久
# import time
# print(time.time())
#
# for x in range(1001):
# for y in range(1001):
# c=1000-x-y
# if x**2+y**2==c**2:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.