text stringlengths 37 1.41M |
|---|
"""The dataloader module creates a snow.txt file from a larger set of text files
then loads the snow.txt file into a dataframe. Once the data is loaded into the
dataframe, functions clean the and prepare the dataframe for analysis."""
#author: Matthew Dunn
#netID: mtd368
#date: 12/12/2015
import os
import numpy as np... |
'''
Authors: Aditi Nair (asn264) and Akash Shah (ass502)
This module contains the Location_Toolkit class, an instance of which represents an iteration of location mode.
In location mode, the user can provide an address or coordinates and a radius. The starting location must be in one
of the cities that appears in ou... |
num_coins = 0
print "You have %d coins." % num_coins
switch = raw_input("Do you want another? (yes/no)")
while switch == "yes":
num_coins += 1
print "You have %d coins." % num_coins
switch = raw_input("Do you want another? (yes/no) ")
print "Bye"
|
offset = 13
secretWord = raw_input("Secret word: ")
alphabet = 'abcdefghijklmnopqrstuvwxyz'
cipher = ''
letter = ''
translation = ''
for x in range(len(alphabet)):
letter = alphabet[x + offset: x + 1 + offset]
cipher += letter
if x == len(alphabet) - offset:
break
for y in range(offset):
lette... |
givenString = raw_input("Word to reverse: ")
newString = ''
holder = ''
for x in range(len(givenString)):
holder = givenString[len(givenString) - 1: len(givenString)]
newString = newString + holder
givenString = givenString[0: len(givenString) - 1]
print newString
|
import random
guess_counter = 1
random_number = random.randint(1, 10)
guess = int(raw_input("Guess a number between 1 and 10"))
play_again = "yes"
while guess_counter < 5:
if guess == random_number:
print "you win!"
play_again = raw_input("Play again? (yes/no)")
if play_again == "yes":
... |
#multiply vectors
given1 = [2, 4, 5]
given2 = [2, 3, 6]
newList = []
for i in range(len(given1)):
newList.append(given1[i] * given2[i])
print newList
|
"""Defined maze classes, MG and items"""
from random import randint
from constants import * #import all constants
class Maze:
"""Definition of labyrinth and items"""
def __init__(self, maze_map, items):
self.maze_map = maze_map
self.items = {}
for item in items:
self.items[... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for index, value in enumerate(nums):
y = target - value
if abs(target)%2 == 0 and y == value:
if len([i fo... |
# coding=utf-8
import collections
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
temp = []
for i in nums1[:]:
if i in nums2[:]:
temp.append(i)
... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
from config import Configuration
from utils import eval_numerical_gradient
class GradientDescent(object):
"""
Abstract Model for Gradient Descent
================
Member Variables
================
learning_ra... |
def home() :
print("\n --- Menu ---")
print("1. Daftar Kontak")
print("2. Tambah Kontak")
print("3. Keluar")
pilih = int(input("Pilih nomor menu : "))
return pilih
def daftar(kontak):
print("\nDaftar Kontak : ")
for i in range(len(kontak)):
print("\nNama : ",kontak[i][0])
... |
#file management functions
import os
import stat
#fifo class
class FIFO(object):
def __init__(self, filePath): #runs at object innitialization
self.filePath = filePath
print('Created '+filePath)
pass
def __str__(self): #So when we call the DataStream object as a string, it will return... |
def FizzBuzzTest(max_range):
for i in range(1, max_range):
if i % 15 == 0:
print(i, "FizzBuzz")
if i % 3 == 0:
print(i, "Fizz")
if i % 5 == 0:
print(i, "Buzz")
print("Start FizzBuzz Test \nInput max range of test: ")
FizzBuzzTest(int(input()))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 7 21:36:14 2018
@author: sunnykarira
"""
# SLR = Fitting a line that best fits the data (linearly)
# y = b0 + b1 * (x)
# y = So this is the dependent variable the dependent variable something you're trying to explain
# x = You're assuming that it ... |
word = raw_input('enter a word: ')
if word.lower() < 'banana':
print 'Your word: ' + word + ', comes before banana'
elif word.lower() > 'banana':
print 'Your word: ' + word + ', comes after banana'
else: print 'All right, bananas'
|
numList = list()
while True:
num = raw_input("Enter a number: ")
if num == "done": break
try:
entry = int(num) #convert from input (string) to integer
except:
print "Invalid input"
continue
if num not in numList:
numList.append(num)
print 'Maximum is', max(numList)
pr... |
#Exercise 7.11
#fungsi string metode find
str ="Hello world"
print("str find o= ", str.find('o'))
print("str find l= ", str.find('l'))
|
import numpy as np
x = np.arange(1, 10)
y = np.arange(1, 10)
# add 2 numpy arrays together
# loops in C and adds the elements at the same index
sum = x + y
squared = x**2
sqrt = np.sqrt(squared) # goes back to your original array x
# get the exponential of the elements in the array
z = np.exp(y)
# get the Eucled... |
import numpy as np
matrix = np.random.randint(1, 10, (5, 5))
# only elements greater than 3
# and returns an array
matrix_2 = matrix[matrix > 3]
# return the even numbers in an array
matrix_3 = matrix[matrix % 2 == 0]
# replace the negative elements with 0 and odd elements wiht 25
x = np.random.randint(-50, 50, (5... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
daily_returns_df = pd.read_csv("../../data/daily_returns.csv")
print(daily_returns_df)
# pick APPL and plot its daily return histogrmas
# i want the mean and the std of the stock
mu = daily_returns_df["AAPL"].mean()
sigma = daily_returns_df["AAPL"... |
'''
* Depth-first search implementation to solve A Knight's Tour problem.
* Initial state: knight occupies, and has only come in contact, with one tile (the starting tile).
* Goal state: all tiles have been occupied once and only once.
* Contributed to by: Ricky Dodd (220010849)
'''
import matplotlib.py... |
# Step 2 - Climate App
# Now that you have completed your initial analysis, design a Flask API based on the queries that you have just developed.\
# Use FLASK to create your routes.
# Routes
# /
# Home page.
# List all routes that are available.
# /api/v1.0/precipitation
# Convert the query results to a Dictionary usi... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
def edge_weight_percolation(network : nx.Graph, order, connecting = 'strong') -> np.ndarray:
'''Percolation with given weight on given network.
Parameters
---------------
network : `nx.Graph` (or `nx.DiGraph`)
The networ... |
#! /usr/bin/python3
# word_jumble.py
# Luke Gosnell
# 10/27/2014
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pi... |
from collections import defaultdict
def adjust_frequency(start_f, sequence):
for f in sequence:
start_f += f
return start_f
def find_repeated_frequency(start_f, sequence, max_iter=150):
freqs = defaultdict(int)
freqs[start_f] = True
while max_iter:
for f in sequence:
st... |
def farenheit2celsius(c):
return round(c * 9/5) + 32
def kelvin2celsius(c):
return round(c * 273.15)
def rankine2celsius(c):
return round(c + 273.15) * 9/5
def main():
c = float(input("celsius:"))
celsius = 10
for c in range (-30 ,60 ,10):
celsius += 10
print ("F:",farenheit2cels... |
def merge_lists(a, b):
"""Return a list containing the unique items combined from a and b, in roughly
the same order they appear in a and b.
The input lists do _not_ need to be sorted, but any items that are common to both lists
should appear in the same order.
For example::
>... |
import numpy as np
class SearchFit(object):
"""Class used for fitting a model multiple times searching across a range of input parameters.
This is a brute-force approach to finding a better fit solution in cases where the standard minimization tools
are likely to become stuck in a local minimum.
... |
"""
The script demonstrates a simple example of using ART with PyTorch. The example train a small model on the MNIST dataset
and creates adversarial examples using the Fast Gradient Sign Method. Here we use the ART classifier to train the model,
it would also be possible to provide a pretrained model to the ART clas... |
def partiton(L, left, right):
current_index=left
while left<right:
while left<right and L[current_index]<=L[right]:
right-=1
L[right],L[current_index]=L[current_index],L[right]
current_index=right
while left<right and L[current_index]>=L[left]:
left+=1
... |
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
index = 0
ss = []
for i in range(len(s)):
if ord('a') <= ord(s[i]) <= ord('z') or ord('0') <= ord(s[i]) <= ord('9'):
ss.appen... |
def binary_search(alist, item):
# 准备工作
n = len(alist)
# 列表空判断
if n == 0:
return False
mid = n // 2
# 中间值匹配
if alist[mid] == item:
return True
# 左侧二分查找
elif item < alist[mid]:
return binary_search(alist[:mid], item)
# 右侧二分查找
else:
... |
from tkinter import *
window = Tk()
window.title("My First GUI Program")
window.minsize(width=500, height=300)
# Label
my_label = Label(text="I am a label", font=("Arial", 24, "bold"))
my_label.pack()
# my_label["text"] = "New Text"
my_label.config(text="New Text")
# Entry: An input component
input_entry = Entry(w... |
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0) # This turns the tracer off. Now the screen will refresh only after screen.... |
import pandas
valar_scores = {
"valar": ["Manwe", "Varda", "Ulmo", "Aule", "Yavanna", "Orome", "Vana"],
"scores": [82, 88, 64, 90, 2, 88, 26]
}
valar_data_frame = pandas.DataFrame(data=valar_scores)
# Looping through a data frame is very similar to looping through a dictionary
# for (valar, score) in valar_d... |
import pandas
import random
import smtplib
import datetime as dt
BIRTHDAYS_CSV_FILE_PATH = "birthdays.csv"
NAME_PLACEHOLDER = "[NAME]"
def is_today(month, day):
"""Check if today matches the provided month and date"""
today = dt.datetime.today()
return (month == today.month) and (day == today.day)
def ... |
# You are going to write a program that calculates the average student height from a List of heights.
# e.g. student_heights : 180 124 165 173 189 169 146
# The average height can be calculated by adding all the heights together and dividing by the total
# number of heights.
# e.g.
# 180 + 124 + 165 + 173 + 189 + 16... |
import pandas
data = pandas.read_csv(filepath_or_buffer="weather_data.csv")
# print(data)
print(type(data)) # DataFrame: https://pandas.pydata.org/docs/reference/frame.html
print("\nTemperature data:")
# print(data["temp"])
print(type(data["temp"])) # Series: https://pandas.pydata.org/docs/reference/series.html
# ... |
import numpy as np
import sys
import argparse
def seive(N):
isPrime = [True] * N # Initialize the list with prime flags
isPrime[0] = isPrime[1] = False # 0 and 1 are not primes
primes = np.array([], dtype=np.int64) # empty array for the primes
for (i, isprime) in enumerate(isPrime):
if isp... |
def shell_sort(unsorted_array, size):
gap = size / 2
gap_index = gap
while gap > 0:
for gap_index in range(gap, size):
temp_item = unsorted_array[gap_index]
insert_index = gap_index
while insert_index >= gap and unsorted_array[insert_index - gap] > temp_item:
... |
import sys
#stolen from http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
# Print iterations progress
def printProgress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100, fill = '█'):
"""
Call in a loop to create terminal progress bar
@params:
ite... |
from array import *
val=array('i',[]) #user defined array
length=int(input("Enter the length of array:"))
for i in range(length):
x=int(input("Enter the value{}==>".format(i)))
print("\n")
val.append(x)
print(val)
|
# loop in squre and cube
for var1 in range(26):
print("NO {}, sqaure is {} and cube is {}".format(var1,var1**2,var1**3))
|
a=5 #101
b=6 #110
#temp=a
#a=b
#b=temp
#a=a+b #11
#b=a-b #5
#a=a-b #6
print("value of A->",a)
print("value of B->",b)
#faster executoin then above 2 bcz its work on bit
a=a^b
b=a^b
a=a^b
#below work on (ROT_TWO()) ::::The function swap the two top most item in stack
#a,b=b,a
p... |
x=int(input("Enter the no1:"))
y=int(input("Enter the no2:"))
#Airthmatic operator
# Addition of numbers
add = x + y
print("Ans=>Add",add)
# Subtraction of numbers
sub = x - y
print("Ans=>Sub",sub)
# Multiplication of number
mul = x * y
print("Ans=>Mul",mul)
# Division(float) of number
div1=(x / y... |
s = "This is String"
s1 = """
Test Multi Line
String
"""
print(s1)
print(s[1])
print(s * 2)
print(len(s))
print(s[0:5]) # This [start index : end index]
print(s[6:]) # s String
print(s[:5]) # This
print(s[-4:-1]) # rin g=-1, n=-2, i=-3, ...
"""
Step Value - defines how many steps to jump in one direction
... |
print(" Multiple \nnLines")
a, b = 10, 20
print(a, b, sep=":")
name = "Dhruv"
marks = 10.5010
print("Name is {} Marks is {}".format(name, marks))
print("Name is {0} Marks is {1}".format(name, marks))
print("Name is %s Marks is %.2f" % (name, marks))
# Reading from console
name = input("Enter Name: ")
# Type Castin... |
import random
# Maze symbol constants
WALL = '#'
OPEN = ' '
PLAYER = 'A'
START_POSITION = (1, 1)
POKEMON = {
'P': 'Pikachu',
'Z': 'Zubat',
'D': 'Doduo',
'R': 'Rattata',
'W': 'Weedle',
'?': '???'
}
GOOD_POKEMON = 'P'
BAD_POKEMON = 'ZDRW'
DIRECTIONS = 'nsew'
DIRECTION_DELTAS = {
'n': (-1... |
#login or create an account
user = ""
accs = open("accs.txt","r")
look = accs.read()
look = look.split("\n")
accs.close()
accs = open("accs.txt","w")
accs.close
def intro():
intq = input("Do you already have an account? Press y if yes; n if no ")
if intq.lower()=="y":
print ("Login")
... |
import pickle
import os
from os import path
#文件复制
def File_Copy(f_1, f_2):
#文件打开
file_1 = open(f_1, "rb")
file_2 = open(f_2, "wb")
#文件复制
pickle.dump(file_1.read(), file_2)
#文件的关闭
file_2.close
file_1.close
#文件遍历
def File_Trav(url_1, url_2):
for i in os.listdir(url_1):
#文件... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 6 08:20:42 2020
@author: 15025
# 您的提交打败了 100.00% 的提交!
"""
class Solution:
"""
@param n: An integer
@return: A list of strings.
"""
def fizzBuzz(self, n):
# write your code here
list1 = []
for i in range(1, n+1)... |
#Tic Tac Toe - Init
#Create box class
class box:
def __init__(self,length = 1, width = 1, height = 1):
self.length = length
self.width = width
self.height = height
#Method to calculate volume
def get_volume(self):
return self.length * self.width * self.height
class sphere:
... |
'''
Created on 09/10/2011
@author: Katcipis
'''
class Identification(object):
'''
Identification abstraction.
'''
def __init__(self, _id):
'''
Identification abstraction.
'''
self.__id = _id
def getID (self):
'''
Get the identification raw ... |
'''
Created on 01/10/2011
@author: katcipis
'''
class PersonConstructionError(Exception):
'''
Simple exception that is raised when a Person
is created with invalid parameters.
'''
def __init__(self, error_msg):
self.error_msg = error_msg
def __str__(self):
return repr(self.er... |
import argparse
import sys
import os
#Specify -h to know the input parameters
try:
arg1 = sys.argv[1]
except IndexError:
print "Usage: " + "python" + os.path.basename(__file__) + " -h"
sys.exit(1)
parser = argparse.ArgumentParser()
parser.add_argument('-add',action='store_true',help="For adding two numb... |
# By: Thomas Welborn (tdw058)
# File: FindingRoots.py
# Description: This program finds the roots of a polynomial using various methods.
# Date Created: 10/15/19
def makeDeriv(exponentsList, coefsList):
derivCoefsList = []
for i in range (0, (len(coefsList) - 1)):
derivCoefsList.append(exponentsList[i] * coef... |
# hkcalc.py
import hktext
def str2num(numstr):
if type(numstr)==int or type(numstr)==float:
return numstr
returnval = 0
multiplier=1
dodivide=False
numdivisions=0
for c in numstr:
if c == '-':
multiplier=-1
elif c=='.':
dodivide=True
elif... |
import random
import re
from cipher import Cipher
class KeywordCipher(Cipher):
def __init__(self):
super().__init__()
self.codeword = input("What codeword would you like?").lower()
re.sub(r'[A-Za-z]+', '', self.codeword)
diff = "".join([letter for letter in self.alphabet if letter ... |
# -*- coding:utf-8 -*-
# Author:wu
# Time: 2018年9月4日 20:16
# 字典
# 一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
""" 使用字典 """
# 访问字典中的值
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
new_points = alien_0['points']
print("You just earned " + ... |
# -*- coding:utf-8 -*-
# Author:wu
# Time: 2018年9月12日 16:10
# 文件和异常
# 导入需要使用的相关模块
import json
""" 存储数据 """
# 使用json.dump()和json.load()
numbers = [2, 3, 5, 7, 11, 13]
filename = '/Users/wuxuhao/Desktop/Python/ReadBooks/Pyhton Crash Course/files/numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers... |
def pridejStudenta():
jmeno = ''
while jmeno == '':
jmeno = input("Zadej jmeno studenta: ")
studenti.append(jmeno)
znamkyH = []
if predmety.count() != 0:
for predmet in predmety:
while True:
znamka = input("Zadej znamku z předmětu %s: " %predmet)
... |
#function to print a diamond and display it on the screen
def diamond(level):
for i in range(0, level):
print ' '*(level-i)+ "*"*i + "*"*(i-1)
for i in range(level,0, -1):
print ' '*(level-i)+ "*"*i + "*"*(i-1)
a=input("Number:")
diamond(a)
|
# -*- coding: utf-8 -*-
import socket
def get_info():
global PORT
PORT = int(input("Please choose the port number: "))
global HOST_NAME
HOST_NAME = socket.gethostname()
global HOST_ADDRESS
HOST_ADDRESS = socket.gethostbyname(HOST_NAME)
print(HOST_NAME)
print(HOST_ADDRESS)
def creat... |
"""An example library for converting temperatures."""
def convert_f_to_c(temperature_f):
"""Convert Fahrenheit to Celsius."""
temperature_c = (temperature_f - 32) * (5/9)
return temperature_c
def convert_c_to_f(temperature_c):
"""Convert Celsius to Fahrenheit."""
temperature_f = (9/5) * temperat... |
"""
*/* *****************************
@Description: Three methods for 'string matching'
@Author: DQ
@LastEditors : DQ
@Date: 2020-03-23 19:09:38
@LastEditTime : 2020-03-24 03:31:51
*/* ******************************
"""
def get_table( s: str ):
"""
*/* *****************************
... |
from enum import Enum
class Hand(str, Enum):
RIGHT = "right"
LEFT = "left"
BOTH = "both"
LEFT_HAND_CHARS = set("QWERTASDFGZXCVB")
RIGHT_HAND_CHARS = set("YUIOPHJKLNM")
def get_hand_for_word(word: str) -> Hand:
"""
Use the LEFT_HAND_CHARS and RIGHT_HAND_CHARS sets to determine
if the passed i... |
import datetime as d
start = d.datetime.now()
def edDistRecursive(a,b):
if len(a) == 0:
return len(b)
if len(b) == 0:
return len(a)
delt =1 if a[-1] != b[-1] else 0
return min(edDistRecursive(a[:-1],b[:-1]) + delt,
edDistRecursive(a[:-1],b) + 1,
edDistRecursive(a,b[:-1]) + 1,
)
dis = edDistRecursive... |
class User:
def __init__(self, username, email_address):
self.name = username
self.email = email_address
self.account = BankAccount(int_rate = 0.02, balance=0)
def make_deposit(self, amount):
self.account.deposit(amount)
return self
def make_withdrawal(self, amount)... |
print("Hello World")
first_name = "Big"
print("Hello",first_name)
print("Hello " + first_name)
fav_num = 69
print("Hello", fav_num)
print("Hello " + str(fav_num))
food_one = 'burrito'
food_two = 'tacos'
print("I love to eat {} and {}".format(food_one,food_two))
print(f"I love to eat {food_one} and {food_two}") |
def add(a:int, b:int):
"""My add function
Args:
a (int): first number
b (int): second number
Returns:
int: the sum of two number
"""
return a + b
def minus(a:int, b:int):
"""My minus function
Args:
a (int): first number
b (int): second number
... |
def partition(arr,l,h):
i = (l-1)
x =(arr[h])
for j in range(l,h):
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[h] = arr[h],arr[i+1]
return(i+1)
def quick_sort(arr,l,h):
size = h-l+1
stack = [0] * (size)
top = -1
top = top+1
stack[top]=l
top = top+1
stack[top]=h
|
import unittest
from src.customer import Customer
from src.drink import Drink
class TestCustomer(unittest.TestCase):
def setUp(self):
self.customer = Customer("Sandy", 10.00, 30, 0)
self.drink = Drink("Tennants", 2.00, 2)
def test_customer_has_name(self):
self.assertEqual("Sandy", self... |
'''
#创建2个类,2个对象
class Handsome_boy():
"""
帅哥
"""
def __init__(self,name="",sex="",height=0):
self.name=name
self.sex=sex
self.height=height
def work(self):
print("IT")
h01=Handsome_boy("A","男",170)
print(id(h01))
h01.work()
h02=Handsome_boy("B","男",160)
print(id(h02... |
"""
二维列表工具
"""
class Vector2:
"""
向量
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# 将函数转移到类中,就是静态方法.
@staticmethod
def right():
return Vector2(0, 1)
@staticmethod
def up():
return Vector2(-1, 0)
@staticmethod
def left()... |
"""
#1.用真值表达式判断奇偶数
num = "偶数" if int(input("请输入整数:")) % 2 == 0 else "奇数"
print(num)
#2.输入一个年份,是闰年给变量day赋值29,赋值28
year = int(input("请输入年份:"))
day = 29 if year%400==0 or year % 4 ==0 and year % 100 != 0 else 28
print(day)
# 输入两个整数,一个作为开始值,一个作为结束值,请输出中间值
num01 = int(input("请输入第一个整数:"))
num02 = int(input("请输入第二个整数:"))
num... |
'''
在控制台中录入5个学生信息(姓名/年龄/性别)
数据结构:列表中嵌套字典
[{"name":xx,
"age":xx,
"sex":xx,},
{"name":xx,
"age":xx,
"sex":xx,}.......]
'''
# list=[]
# d01={}
# for i in range(2) :
# d01[i]={"name":str(input("请输入姓名:")),
# "age":int(input("请输入年龄:")),
# "sex":str(input("请输入性别:"))}
# list.append(d01[i]... |
"""
sql语句传参练习
"""
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost',
port=3306,
user='root',
passwd='123456',
database='stu', # 数据库名
charset='utf8')
# 创建游标
cur=db.cursor()
while True: # 手动输入
name ... |
from multiprocessing import Process
from time import sleep
# 带参数的进程函数
def worker(sec, name):
for i in range(3):
sleep(sec) # 每过2s执行一次
print("I'm %s" % name)
print("I'm working...")
# p = Process(target=worker,args=(2,'Baron')) # 给target函数位置传参(元组)
# p = Process(target=worker,kwargs={'name... |
"""
#练习1.("悟空","八戒","沙僧","唐僧")
list01=["悟空","八戒","沙僧","唐僧"]
iterator = list01.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except:
break
print("..........................................")
######################
dict01={"张三丰":101,"张无忌":102,"赵敏":102}
iterator = dict0... |
"""
队列的顺序存储
"""
# 队列异常
class QueueError(Exception):
pass
# 完成队列操作
class SQueue:
def __init__(self):
self._elems = [] # 使用列表存储队列数据
# 判断是否为空
def is_empty(self):
return self._elems == []
# 入队
def enqueue(self, elem):
self._elems.append(elem)
# 出对
def dequeue(sel... |
# 文件的读操作
# 打开文件返回文件对象
fd=open('test','r')
# #读操作
while True:
data01=fd.read(8)
# 如果文件读到空表示文件已经读完
if not data01:
break
print("read读取到的内容:")
print(data01) # 换行也算一个字符
# 读取一行内容
data02=fd.readline(4)
#data02=fd.readline() # 会读取上一行剩下的字符 # o
print("readline读取到的内容:")
print(data02)# hell
#... |
# 死锁事例二
# 重复上锁造成死锁
from threading import Thread,RLock
import time
num = 0 # 共享资源
lock = RLock() # 解决方法,使用重载锁,可以允许重复上锁
class MyThread(Thread):
def fun01(self):
global num
with lock:
num -= 1
def fun02(self):
global num
if lock.acquire():
num += 1
... |
list01=["a","b","c"]
list02=[101,102,103]
list03=["张三丰","张无忌","赵敏"]
# for item in enumerate(list):
# print(item)
#
# for index,element in enumerate(list):
# print(index,element)
def my_enumerate(target):
index=0
for item in target:
yield index,item
index+=1
for item in my_enumerate(lis... |
# 死锁事例一
import time
import threading
#交易类
class Account:
def __init__(self,_id,balance,lock):
self.id=_id # 用户
self.balance=balance # 存款
self.lock=lock # 锁
# 取钱
def withdraw(self,amount):
self.balance -= amount
# 存钱
def deposit(self, amount):
self.balanc... |
import asyncio
import time
now = lambda: time.time()
async def do_work(x):
print('Waiting:', x)
await asyncio.sleep(x) # 协程跳转
return "Done after %s s" % x
start = now()
# 协程对象
cor1 = do_work(1)
cor2 = do_work(2)
cor3 = do_work(3)
# 将协程对象生成一个可轮循跳转的对象列表
tasks = [asyncio.ensure_future(cor1),
a... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 02:19:07 2020
@author: k.kirilov
"""
import random as rm
def zoneCreator():
#function that creates objects of the zone class
pass
class Nation:
#Nations start with 1 or 2 zones, or 1 or 2 cities ,and then try to conquer more (to conquer a zon... |
from random import randint as rint
import sys
import math
# RSA key fun stuff
# Reference: https://www.di-mgt.com.au/rsa_factorize_n.html
# Try to find factor of n given a random g
def factor_n(k, g, n):
t = k
if t % 2 == 0:
t = t / 2
x = (g**t) % n
y = math.gcd(x-1, n)
if x > ... |
# project euler challenge 4
largest = 0
for num1 in range(100, 1000):
for num2 in range(100, 1000):
x = num1 * num2
x = str(x)
reverse = x[::-1]
if reverse == x:
if int(x) > largest:
largest = int(x)
print(largest) |
# Exercise 4.1
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
#1
def square(t):
for i in range(4):
fd(t,100)
lt(t)
square(bob)
#2
def square2(t,l):
for i in range(4):
fd(t,l)
lt(t)
x = int(raw_input("Enter Length : "))
square2(bob,x)
#3
def polygon... |
class Coche():
def __init__(self): #constructor (self.)
self.__largoChasis=250 #encapsuladas(__)
self.__anchoChasis=120
self.__ruedas=4
self.__enmarcha=False
def arrancar(self,arrancamos):
self.__enma... |
"""print("Programas de becas")
distancia_escuela=int(input("Introduce la distancia a la escuela en km"))
print(distancia_escuela)
numero_hermanos=int(input("Introduce el n° de hermanos en el Instituto"))
print(numer_hermanos)
salario_familiar=int(input("Introduce el salario anual bruto"))
print(salario_famili... |
from run import LinkedList
class TestLinkedList:
def test_it(self):
items = ["one", "two", "three"]
it = LinkedList()
for item in items:
it.add(item)
for expected, actual in zip(items, it):
assert expected == actual.item
assert True
def test_it_... |
# Build Model
# Build the Neural Network
# Neural networks comprise of layers/modules that performm operations on data.
# "torch.nn" namespace provides all the building blocks you need to build your own neural network.
# every module in PyTorch subclasses the "nn.MModule".
# neural network is a module that consists of... |
class CoffeeMachine:
water = 400
milk = 540
coffee_beans = 120
disposeable_cups = 9
money = 550
def __init__(self, water, milk, coffee_beans, disposeable_cups, money):
self.water = water
self.milk = milk
self.coffee_beans = coffee_beans
self.disposeabl... |
"""type based dispatch"""
class box:
width=0
height=0
area=0
def __init__(self,w,h):
self.width=w
self.height=h
self.area=w*h
def show(self):
print 'area of box is',self.width*self.height
def __add__(self,other):
if isinstance(other,box):
... |
fname=raw_input("enter a file name:")
fd=open(fname)
email=dict()
for line in fd:
if line.startswith('From:'):
line=line.split()
e=line[1]
if e not in email:
email[e]=1
else:
email[e]+=1
print email
maxx=0
maxemail=' '
for k in email:
if email[k]>maxx:
... |
"""
Create a program to look for lines of the form:
We just received $50.00 for 10 cookies.
We just received $20.00 for 2 dolls.
We just received $30.00 for 5 bats.
We just received $15.00 for 11 tattoos.
and extract the amount with dollar sign from
each of the lines using a regular expression.
Count and print the num... |
def computepay(h,r):
if h>40:
return h*r*1.5
else:
return h*r
hour=input("enter hours")
rate=input("enter rate")
result=computepay(hour,rate)
print 'gross pay=',result
|
def prime(n):
for i in range(2,n):
if n%i==0:
return 0
else:
continue
return n
num=input("enter a number:")
result=prime(num)
if result!=0:
print num," is a prime number"
else:
print num, "is not a prime number"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.