text stringlengths 37 1.41M |
|---|
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
x = argv[1]
y ... |
from PIL import Image, ImageDraw, ImageFont
import string
import random
def random_letters(cnt):
return ' '.join(random.choice(string.ascii_letters) for x in range(cnt))
def draw(letters):
# Set the size of the image
width = 100
height = 40
# Generate an image
im = Image.new("RGB", (width, ... |
"""
第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
北京
程序员
公务员
领导
牛比
牛逼
你娘
你妈
love
sex
jiangge
"""
import os
path = os.listdir(".")
def load_filter_words(path):
words=[]
with open(path, 'r', encoding='utf-8') as content:
words = content.read()
return ... |
def ip_divider():
"""
Divides IP number segments and return separate segments with its lengths.
"""
ip_address = input("Please enter the IP address: ")
ip_address_dot = ip_address + "."
segment = ""
ip_segments = []
print("")
for char in ip_address_dot:
if char != ".":
... |
list1 = [10, 21, 4, 45, 66, 93]
for number in list1:
if number % 2 == 0:
print(number, end = " ")
|
def insertionSort(lst):
for i in range(1, len(lst)):
curr = lst[i]
j = i - 1
while j >= 0 and curr < lst[j]:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = curr
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("% d" % arr[i]) |
class Square():
def __init__(self, s):
self.s1 = s
square_one = Square(5)
square_one_sm = square_one
def object_is(obj1, obj2):
if obj1 is obj2:
return True
else:
return False
print(object_is(square_one, square_one_sm)) |
#!/usr/bin/env python3
from VectorOperations import ScalarMultiplication as scalar
# Suppose A and B are matrices of the n x n, A + B = C is the C[i][j] = A[i][j] + B[i][j]
def Addition(A, B):
row = len(A)
col = row
C = [[0]* row for _ in range(row)]
for i in range(row):
for j in range(col):
... |
#!/usr/bin/env python3
import cmath
# find the roots of a function in the form of aX^2 + bX + c = 0
# findRoots takes three parametes.
def findRoots(a,b,c):
sqrt1 = (b**2) - (4*a*c)
denom = 2*a
negB = -b
solutionList = []
sol1 = (negB - cmath.sqrt(sqrt1))/denom
sol2 = (negB + cmath.sqrt(sqrt... |
from collections import namedtuple,OrderedDict
Person = namedtuple('Person','id Name LastName age')
a_person = Person(id=14253083,Name='Edgar',LastName='Ocampo',age=32)
print(a_person) # I can acces them by index []
# Next example with OrderedDict :: Order the dict in falling way
d = {'banana' : 3, 'apple' : 4, '... |
def find_location(board):
x = 0
y = 0
for i in range(len(board)):
for ii in range(len(board)):
if board[i][ii] == 1:
x = ii
y = i
return x, y
def posible_moves(x, y, board_size):
posible_moves_array = []
if y > 0:
posible_moves_arr... |
# Print out a string depending on if food is a value in bakery_stock print out a string that states how many items are left.
# This code picks a random food item:
from random import choice
food = choice(["cheese pizza", "quiche","morning bun","gummy bear","tea cake"])
bakery_stock = {
"almond croissant" : 12,
... |
import random
random_number = random.randint(1,10) # numbers 1 - 10
# handle user guesses
# if they guess correct, tell them they won
# otherwise tell them if they are too high or too low
# Let player play again if they want!
while True:
player = int(input("Guess a number between 1 and 10: "))
if pla... |
from cs50 import get_string, get_int
import re
options = [1, 2, 3, 4, 5, 6, 7, 8]
i = None
while i not in options:
i = get_int("Height: ")
spaces = i - 1
for a in range(i):
hashes = a + 1
for b in range(spaces):
print(" ", end="")
for c in range(hashes):
print("#", end="")
prin... |
#!/bin/python
import math
DIGITS=int(input("How many digitsyou want :"))
print "%.*f" %(DIGITS,math.pi)
|
'''
Calcule a potência de x elevado a n pot(x, n). Ex.: pot(2, 3) = 8.
'''
def pot(a, b):
if b == 1:
return a
if b > 1:
return a * pot(a, b - 1)
print(pot(2,3))
|
import sys
# =============================== Task 1 ===============================
print('=' * 30, ' Task 1 ', '=' * 30)
# Run-app from terminal: python Homework_4.py 8 12.50 100
def validate_args(arguments):
if len(arguments) != 4:
print('Error, expecting 3 parameters:\n'
'Hours, Hourly ... |
import sqlite3
from db import db
# ovaj UserModel je API! (nije rest)
# sastoji se od 2 API endpoint methods find_by_username i by_id
class UserModel(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50))
password = db.Column(db.String(50))... |
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
create_table = "CREATE TABLE IF NOT EXISTS users" \
"(id INTEGER PRIMARY KEY, username text, password text, email text)"
# for auto increment use INTEGER, otherwise int is enough
cursor.execute(create_table)
create_ta... |
class Node:
def __init__(self, v):
self.value = v
self.prev = None
self.next = None
class OrderedList:
def __init__(self, asc):
self.head = None
self.tail = None
self.__ascending = asc
def compare(self, v1, v2):
if v1 < v2:
return -1
elif v1 == v2:
return 0
else:
return +1
def add(se... |
#Made of merge and sort. Merge only merges two SORTED lists
#Break a list of length n into n 1 length lists (inherently sorted) and then merge them 2 at a time
#Has a space of 0(n) complexity, time to break is O(logn) time to put back is O(n) therefore total time complexity is O(nlogn). Most efficient you can make a s... |
#Bubble sort compares values and switches them if the value later on is lower
def bubble_sort(list_):
for i in range(len(list_) - 1, 0, -1):
for j in range(i):
if list_[j] > list_[j + 1]:
list_[j], list_[j + 1] = list_[j + 1], list_[j]
return list_
ex_list = [5, 4, 7, 0, 1, ... |
# coding:utf-8
import os
import numpy as np
import matplotlib.pyplot as plt
class lr_classifier(object):
"""
使用梯度上升算法 LR 分类器
"""
@staticmethod
def sigmoid(x):
"""
:param x: sigmoid function
:return:
"""
return 1.0 / (1 + np.exp(-x))
def gradient_ascen... |
# Assignment: Names
# Write the following function.
# Part I
# Given the following list:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}... |
class Animal:
def __init__(self, esperanzaVida, nombre):
self._esperanzaVida = esperanzaVida
self._nombre = nombre
class Invertebrados (Animal):
def __init__(self, habitat, esperanzaVida, nombre):
self.habitat = habitat
Animal(esperanzaVida, nombre)
class Vertebrados (Animal):
def __init__(self,... |
class PlaylistIterator:
"""Iterator for class Playlist"""
def __init__(self, playlist):
self._songs = playlist.songs
self._index = 0
def __next__(self):
if self._index < len(self._songs):
song_obj = self._songs[self._index]
self._index += 1
retur... |
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metric... |
import numpy as np
from quaternion import *
from rotation_matrix import *
class Transform(object):
"""
Homogeneous transform object
:Example:
T = Transform(np.zeros(3), Quaternion())
>>> quaternions = [Quaternion(q/np.linalg.norm(q)) for q in np.random.rand(5,4)]
>>> positions = [p for p in n... |
from threading import Thread
i = 0
def someThreadFunction1():
global i
while i<1000000:
i+=1
print ("first\n")
def someThreadFunction2():
global i
while i<1000000:
i+=1
print ("second\n")
def main():
someThread1 = Thread(target = someThreadFunction1, args = (),)
someThread1.start()
someThread2 = Thr... |
__author__ = 'Pato'
class Program:
def __init__(self, a_name):
self.instructions = []
self.program_name = a_name
self.program_size = 0
self.instructions.append('EOF')
def run(self):
for i in self.instructions:
i.execute()
def get_instructions(self):
... |
# Prompt: Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
def is_unique(val : str) -> bool:
copy = val
for i in val:
copy = copy[1:]
if i in copy:
return False
return True
assert(is_unique("aaaa") ... |
# Prompt: Given an image represented by an NxN matrix, where each pixel is 4 bytes,
# write a method to rotate the image 90 degrees. Can you do this in place?
def rotate(img : [[]]) -> [[]]:
layers = int((len(img)/2)+0.5)
offset = 0
for i in range(0, layers):
for j in range(0, len(img)-1-(offset*2... |
# Prompt: Given a string, write a function to check if it is a permutation of a palindrome.
# A palindrome is a word or phrase that is the same forwards and backwards.
# A permutation is a rearrangement of letters.
# The palindrome does not need to be limted to just dictionary words
# Ex:
# Input: Tact Coa
# Outpu... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 6 17:15:02 2020
@author: Yusef Quinlan
"""
from tkinter import*
from tkinter import ttk
import os
import PyPDF2
from gtts import gTTS
#Make a main window
Main = Tk()
Main.title("ConvertPDFtoMp3")
#C:\Users\User\Downloads so I can see my directory name for test... |
num=int(input("Whos factorial do u want?"))
def recur(num):
if num==1:
return num
else:
return num*recur(num-1)
print("The factorial is", recur(num)) |
def shortNOT(val):
return (~(val & 65535) & 65535)
def shortLSHIFT(val, shift):
return ((val & 65535) << shift) & 65535
def shortRSHIFT(val, shift):
return ((val & 65535) >> shift) & 65535
def shortAND(val1, val2):
return (val1 & 65535) & (val2 & 65535)
def shortOR(val1, val2):
return (val1 & 65... |
"""
App for nonlinear_vector_field.py
TODO:
Need to implement moving the plot view and zooming out
with the mouse. Initial attempts at this implementation
are found in the commented out parts of code.
Setup different ways to plot trajectories, such
as plotting multiple trajectories.
"""
import tkinter as tk
from ... |
def main():
n = int(input())
binary = str(bin(n)).replace("0b", "").split("0")
biggest = 0
for i in binary:
if len(i) > biggest:
biggest = len(i)
print(biggest)
if __name__ == '__main__':
main() |
if __name__ == '__main__':
s = input()
alnum = False
alpha = False
digit = False
lower = False
upper = False
for i in s:
if i.isalnum() == True:
alnum = True
if i.isalpha() == True:
alpha = True
if i.isdigit() == True:
digit = Tru... |
list=[]
l2=[]
m=[]
l3=[]
def Remove(l2):
final_list = []
for num in l2:
if num not in final_list:
final_list.append(num)
return final_list
n=int(input())
for i in range(0,n):
l=[]
list.append(l)
for i in range(0,n):
for j in range(0,2):
a=input... |
def addJob(jobName,jobType,jobExp,jobGoden):
file_data = ""
num = 0
with open("Storage/Job.csv", "r") as f:
for line in f:
line_list = line.strip("\n").split(",")
if line_list[0] != "任务编号":
num = int(line_list[0])
file_data += line
with open(... |
# author: Qiyi Shan
# date: 3.3.2017
from Homework.newsplit import new_split_iter
def priority(operator):
if operator in '+-':
return 1
elif operator in '*/':
return 2
elif operator == '**':
return 3
elif operator == '(':
return 4
elif operator == ')':
return 0
elif operator == '=':
return -1
else:... |
from Homework.infix2 import eval_infix
from Homework.newsplit import new_split_iter
from random import randint
operators = ["+", "-", "*", "/"]
# operators = ["+", "-", "*", "/", "**"]
def rand_num():
return str(randint(1, 6)) if randint(1, 2) == 1 else str(randint(-6, -1))
def rand_space():
return " " * randi... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['figure.figsize'] = (15, 5)
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', 60)
df = pd.read_csv('./data/311-service-requests.csv')
# we select the first five rows to see how the file looks like
print(df[:5... |
# Grace Kelly 11-02-2018
# Source: https://docs.python.org/3/tutorial/controlflow.html#if-statements
x = int(input("Please enter an integer: "))
if x < 0: # if statement if x is less than zero
x = 0 # x is equal to zero, one = sign is defining character
print('Negative changed to zero') # output if x is less than ... |
#Grace Kelly
#https://projecteuler.net/problem=1
#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 the sum of all the multiples of 3 or 5 below 1000.
x = 1
for i in range(1000): # all natural numbers below 1000
if i % 3 == 0 or i %... |
isim=input("İsminizi giriniz->")
print(isim)
sayı1=float(input("İlk sayıyı giriniz->"))
sayı2=float(input("İlk sayıyı giriniz->"))
print(sayı1)
print(sayı2)
topla=sayı1+sayı2
print(topla)
print(type(topla))
dönüşüm=int(topla)#float cinsi verilen sayıyı inte cevirdik.
print(type(dönüşüm))
|
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:return 0
len_list = len(nums)
i = 0
for j in range(1,len(nums)):
if nums[i] != nums[j]:
nums[i+1] = nums[j]
... |
import math
import numpy
class Solver:
def __init__(self):
self.foundSolution = False
def canPlaceNumber(self, sudokuGrid, row, column, number):
for r in range(9):
if(sudokuGrid[r][column] == number):
return False
for c in range(9):
if(sudokuGri... |
#12)“Mă iubeşte un pic, mult, cu pasiune, la nebunie, de loc, un pic,…”. Rupând petalele unei margarete cu x petale, el (ea) mă
#iubeşte …. Exemplu: Date de intrare: x=10 Date de ieşire: … de loc.
a=int(input("nr de petale: "))
b="Ma iubeste un pic"
f="Ma iubeste mult"
c="Ma iubeste cu pasiune"
d="Ma iubeste la n... |
#10)La ferma de găini Copanul este democraţie. Fiecare găină primeşte exact acelaşi număr de boabe de porumb. Cele care nu pot
#fi împărţite vor fi primite de curcanul Clapon. Să se spună cine a primit mai multe boabe şi cu cât. În caz de egalitate, se va
#afişa numărul de boabe primite şi cuvântul "egalitate". Datel... |
def calcVolmSfera(radio):
return 4 / 3 * 3.14 * radio ** 3
r = float(input('Set the radio of sfera: '))
result = calcVolmSfera(r)
print(result)
|
#!/usr/local/bin/python3
# Usage: cat a column of numbers into the program
import sys
from statistics import mean, median, stdev
data = [float(i.strip('\n')) for i in sys.stdin]
print('''Count: {0}
Mean: {1:.2f}
Low: {2}
High: {3}
Median: {4}
Stdev: {5:.2f}'''.format(len(data),
mean(data),
... |
import numpy as np
from Encriptator import *
from diccionario import Diccionario
#Prueba array de numpy
'''
x = np.array([[0,0,0],[0,0,0],[0,0,0]])
print(x)
'''
#Prueba metodo cargarMensaje(mensaje)
'''
texto = 'TexTo De pRuEba'
mensaje = Mensaje(texto)
print(mensaje)
encriptado = Encriptador().cargarMensaje(mensaje)... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
Dongyu Zhu
dybrave@bu.edu- term project- A interesting penalty shootout game
"""
from random import choice
score = [0, 0]
rest = [5, 5]
direction = ['left', 'center', 'right']
def kick():
print ('==== You Kick! ====')
print ('Choose one side to shoot... |
#!/usr/bin/python
class Node:
def __init__( self, value, id, parent_id, position ):
self.id = id
self.parent_id = parent_id
self.value = value
self.position = position # Relative to parent: L - Left, R - Right
self.left = None
self.right = None
def print_no... |
name=input("YOUR FULL NAME: ")
for letter in name:
if letter==" ":
break
print (letter)
|
'''
Johnny Dollard
Programming 1
Pygame Lab
'''
import pygame
import sys
from math import pi
pygame.init()
screen = pygame.display.set_mode((640,480))
white = (255,255,255)
screen.fill(white)
yellow = (255,255,0)
orange = (255,69,0)
green = (0, 255, 0)
blue=(0, 0, 255)
red = (255, 0 , 0)
eye1=(180,70,100,70)
eye2=... |
'''
Assignment Number 1
Due Date: 8/29/16
Name: Johnny Dollard
'''
num=int(input("Numerator: "))
den=int(input("Denominator: "))
ans=num/den
print(num,"/",den,"=",ans)
|
def merge_sort(arr, beg, end):
if beg < end:
mid = (beg + end) // 2
merge_sort(arr, beg, mid)
merge_sort(arr, mid + 1, end)
merge(arr, beg, mid + 1, end)
return
def merge(arr, start1, start2, end):
l1 = [i for i in arr[start1:start2]]
l2 = [j for j in arr[start2 : end... |
people = {
"Alice":{
"phone": 1234,
"addr": "Rockland 23"
},
"Bob":{
"phone": 2344,
"addr": "Kim str 24"
}
}
labels = {
"phone": "phone number",
"addr": "address"
}
name = input("Input the name: \n")
request = input ("Phone number(p) or address(a)?\n")
if reques... |
def celsius_to_farenheit(stopnie):
return (stopnie * 1.8) + 32
def farenheit_to_celsius(stopnie):
return (stopnie - 32) / 1.8
for x in range(-20, 40, 5):
print('Temperatura {celcius}C to {farenheit}F'.format(celcius=x,
farenheit=celsius_to_farenhei... |
from typing import Union, Sequence
def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]:
"""
Calculate min cost of getting to the top of stairway if agent can go on next or through one step.
:param stairway: list of ints, where each int is a cost of appropriate step
:return: ... |
x = 1
while( x < 4):
print("it true")
x=x+1
|
inputs=eval(input("enter the year you were born"))
cal=2019-inputs
if inputs==2016 or inputs==2020:
print("your year was a leap year")
print(cal)
else:
print("your are not a leap year born")
print(cal) |
def even():
for i in range(12,20):
if(i%2==0):
print(i)
even() |
def get_age():
age=input("enter your age")
print("your name is :")
print(age)
def get_name():
name=input("enter your name")
print("your name")
print(name)
def both():
get_age()
get_name()
|
import numpy as np
import pandas as pd
from bokeh.plotting import figure, output_notebook, show
def bokeh_hist(arr, do_log=True, title="A Histogram"):
'''
Always spend 10 mins googling how to bokeh a histogram.
Lets have a quick one!
Inputs:
arr (iterable)
Outputs:
bokeh figure o... |
s=raw_input()
res=""
for i in range(0,len(s)):
if(i==0):
res+=s[i].upper()
elif(s[i-1]==" "):
res += s[i].upper()
# continue
else:
res+=s[i]
print (res) |
# 有偏估计和无偏估计
from playStats.descriptive_stats import mean,variance
import random
import matplotlib.pyplot as plt
def variance_bias(data):
"""方差"""
n = len(data)
mean_value = mean(data)
# 最后除以n或是n-1,有讲究
return sum((e - mean_value) ** 2 for e in data) / n
def sample(num_of_samples,sample_sz,var):
data = []
... |
import hashlib
import random
from random import randint
chars = '0123456789abcdefghijklmnopqrstuvwxyz' # all possible characters
msg = 'Me gusta el helado'
def random_string(): # generate a random string of random length up to 50
randomLength = randint(1, 50)
randomString = ''.join(random.choice(ch... |
"""
Custom class to define data structure for a Black Jack hand.
"""
import constants as cn
from num_to_card_converter import convert, value
class Hand(object):
"""
Class containing all relevant methods for a BlackJack Hand.
"""
def __init__(self, deal_size, deck):
"""
Constructor for... |
# simple Perceptron:
# one input layer and one output layer
# using one hidden layer
# feed-forward and back-propagation steps
from sklearn import datasets
from matplotlib import pyplot as plt
import numpy as np
np.random.seed(0)
feature_set, labels = datasets.make_moons(100, noise=0.10)
plt.figure(figsize=(10,7))
p... |
def outer_func(msg):
message = msg
def inner_func():
print(message)
return inner_func
hi_func = outer_func('Hi')
hello_func = outer_func('Hello')
hi_func()
hello_func()
print ([n**2 for n in range(10) if n%2])
lst = [-1, 1, -2, 20, -30, 10]
lsta = [x[1] for x in sorted(... |
print "Some Math here"
print "8%4: ", 8 % 4
print "8/4: ", 8 / 4
print "8*4: ", 8*4
print "8+4: ", 8+4
print "8-4: ", 8-4
print "56/13: ", 56/13
print "Notice that the last answer is in whole numbers. That is, the result is automatically floored. We need to use floating point numbers (i.e. with decimal points) to get ... |
def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
def addition():
x = int(raw_input("Please enter the first number to be added: "))
y = int(raw_input("Please enter the second number to be added: "))
#return x+y
z = x+y
return z
|
#lyrics = "Hey you"
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
#print lyrics # Doesn't print hey you..?
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to ... |
# Three ways to call things
# dict style
mystuff = {"apples": "Here are apples!"}
print mystuff['apples']
# module style
'''
In some module mystuff:
def apple():
print "I AM APPLES!"
# this is just a variable
tangerine = "Living reflection of a dream"
'''
#import the file
#mystuff.apples()
#print mystuff.tangerine
... |
# 1238765 = 1+2+3+8+7+6+5 = x
n = int(input("Enter the number: "))
sum = 0
while n!=0:
digit = n % 10
sum += digit
n = n // 10
print(sum) |
a = 4
b = 5
temp = 0
print("before :")
print(a)
print(b)
temp = a
a = b
b = temp
print("After: ")
print(a)
print(b)
|
from hashTable import HashTable
import unittest
class HashTableTest(unittest.TestCase):
def test_init(self):
ht = HashTable(4)
assert len(ht.buckets) == 4
assert ht.length() == 0
def test_length(self):
ht = HashTable()
assert ht.length() == 0
ht.set('I', 1)
... |
weight = input("What is your weight? ")
height = input("What is your height? ")
BMI = 703*(int(weight)/int(height)**2)
print("Your BMI is "+ str(BMI) + ".")
if ((BMI) <= 18):
print ("You are underweight.")
elif(((BMI) > 18) and ((BMI) < 26)):
print ("Your weight is normal.")
else:
print ("You are overwight.") |
print("-----------------------------\n"
"------Assignment part 2------\n"
"-----------------------------\n")
print("===You have 3 tries===\n"
"------Be careful------")
print("Iftiaj Alom")
print("1001956795")
import sys
count = 0
while count <3: #count number of tries
option = input("Enter an... |
if x == 3:
print("Hey!")
elif x > 5:
if x < 20:
print("Haha")
else:
print("Wow")
else:
print("No!")
|
from abc import ABC
from typing import Any
class Operator(ABC):
"""
Abstract class for operators, you can create custome operators using it.
"""
pointers = []
"""A list of chars that point to the operator
"""
members = []
"""Members which operation gose over them
"""
... |
def addition(a,b):
if type(a) and type(b) == (str): #or type(a) and type(b) == (int) or type(a) and type(b) == (int):
print (a+b)
else:
print "error"
addition(str(3),5)
#addition(0,4)
|
# 创建一个列表,其中包含数字1~1000000,再使用min()和max()核实该列表确实是从1开始,到1000000结束的。
# 另外,对这个列表调用函数sum(),看看Python将一百万个数字相加需要多长时间
numbers = list(range(1, 1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers)) |
class User1():
def __init__(self,first_name,last_name,*info):
self.first_name=first_name
self.last_name=last_name
self.info=info
def describe_user(self):
print(self.last_name+" "+self.first_name+" has these info:")
for i in self.info:
print(i)
def greet_us... |
# 6-9 喜欢的地方:
# 创建一个名为favorite_places的字典。
# 在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。
# 为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。
# 遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_place = {
'Tom': ['London', 'Liverpool'],
'Jerry': ['NewYork','Liverpool'],
'David':['London','NewYork']
}
for key, value in favorite_place.items():... |
# 如果你可以邀请任何人一起共进晚餐(无论是在世的还是故去的),你会邀请哪些人?
# 请创建一个列表,其中包含至少3个你想邀请的人;然后,使用这个列表打印消息,邀请这些人来与你共进晚餐。
dinner_friend = ['bai', 'ye', 'xie', 'zhu']
print("Hi,"+dinner_friend[0]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[1]+",I want to have a dinner with you")
print("Hi,"+dinner_friend[2]+",I want to have a di... |
# 8-12 三明治:
# 编写一个函数,它接受顾客要在三明治中添加的一系列食材。
# 这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。
# 调用这个函数三次,每次都提供不同数量的实参。
def addtopping(*toppings):
print('You add topping fllow these:')
for topping in toppings:
print(topping)
addtopping('mushrooms','ham')
addtopping('egg') |
# 通过给函数range()指定第三个参数来创建一个列表,其中包含1~20的奇数;再使用一个for循环将这些数字都打印出来
for value in range(1, 20, 2):
print(value)
|
# 编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来
# 对于下面列出的各种测试,至少编写一个结果为True和False的测试。
# ·检查两个字符串相等和不等。
# ·使用函数lower()的测试。
# ·检查两个数字相等、不等、大于、小于、大于等于和小于等于。
# ·使用关键字and和or的测试。·测试特定的值是否包含在列表中。
# ·测试特定的值是否未包含在列表中。
car1 = 'audi'
car2 = 'toyota'
car3 = 'audi'
car4 = 'Audi'
print('Is car1==car2,I guess False')
print(car1 == car2)
prin... |
#6-2 喜欢的数字:使用一个字典来存储一些人喜欢的数字。
# 请想出5个人的名字,并将这些名字用作字典中的键;
# 想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。
# 打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
favorite_number = {'Li': 16, 'zhang': 1, 'wang': 2, 'zhu': 3, 'bai': 4}
print('Li,is ' + str(favorite_number['Li']) + ' your favorite_number')
print('zhang,is ' + str(favorite_number['zh... |
# 10-9 沉默的猫和狗:
# 修改你在练习10-8中编写的except代码块,让程序在文件不存在时一言不发。
try:
with open('cats.txt') as file_object:
print(file_object.read())
except FileNotFoundError:
pass
try:
with open('../dogs.txt') as file_object:
print(file_object.read())
except FileNotFoundError:
pass
|
# 继续使用练习3-1中的列表,但不打印每个朋友的姓名,而为每人打印一条消息。每条消息都包含相同的问候语,但抬头为相应朋友的姓名
names = ["bai", "zhu", "ye", "zhang"]
print("Hello,my good friend "+names[0])
print("Hello,my good friend "+names[1])
print("Hello,my good friend "+names[2])
print("Hello,my good friend "+names[3])
|
# 9-5 尝试登录次数:
# 在为完成练习9-3而编写的User类中,添加一个名为login_attempts的属性。
# 编写一个名为increment_login_attempts()的方法,它将属性login_attempts的值加1。
# 再编写一个名为reset_login_attempts()的方法,它将属性login_attempts的值重置为0。
# 根据User类创建一个实例,再调用方法increment_login_attempts()多次。
# 打印属性login_attempts的值,确认它被正确地递增;
# 然后,调用方法reset_login_attempts(),并再次打印属性login_attemp... |
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
class Stack():
... |
#AMM Tail Animator - amm_ta
#Purpose: To give characters without tail animations tail animations
import struct
import math
import os
def bsk_type():
#Let's the user select bin type
print("Main BSK (Large in size with AMMs) or Special BSK (Small in size w/o AMMs)?(M/S):")
b_type = input("")
... |
import re
import os
# text file to open
file=os.path.join("raw_data","paragraph_1.txt")
# Open txt file
with open(file,'r',encoding="UTF-8") as text:
print(text)
# assigning as an object of text.read class
lines=text.read()
# Counting Words
words=lines.split()
no_of_words=len(words)
# Counting no of peri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.