text stringlengths 37 1.41M |
|---|
# 괄호를 사용하여 튜플을 생성하기.
my_tuple = ('x', 'y', 'z')
print("Output #93: {}".format(my_tuple))
print("Output #94: my_tuple has {} elements".format(len(my_tuple)))
print("Output #95: {}".format(my_tuple[1]))
longer_tuple = my_tuple + my_tuple
print("Output #96: {}".format(longer_tuple))
|
string1 = "This is a "
string2 = "short string."
sentence = string1 + string2
print("Output #18: {0:s}".format(sentence))
print("Output #19: {0:s} {1:s}{2:s}".format("She is", "very "*4, "beautiful."))
m = len(sentence)
print("Output #20: {0:d}".format(m))
|
# lower, upper, capitalize
string6 = "Here's WHAT Happens WHEN You Use lower."
print("Output #34: {0:s}".format(string6.lower()))
string7 = "Here's what happens when You Use UPPER."
print("Output #35: {0:s}".format(string7.upper()))
string5 = "here's WHAT Happens WHEN you use Capitalize."
print("Output #36: {0:s}".for... |
import unittest
from typing import List
from code import PrimeFactors
class TestPrimeFactors(unittest.TestCase):
def _test_prime_factors(self, input: int, expected: List[int]):
obj = PrimeFactors(input)
self.assertEqual(obj.result, expected)
def test_number_one(self):
self._test_prime... |
def sudoku_solve(board):
print 'puzzle'
for line in board:
print line
print
for i in range(9):
for j in range(9):
if board[i][j]!=".":
#print i,j
if check(board,i,j,board[i][j]) == False:
return False
print 'Valid Sudoku'
... |
'''
This is the pgenx.py module, providing the PGenX class. PGenX is a random password generator.
It also includes a database so that every user can have their password saved for future use.
'''
import random
import string
class PGenX:
def __init__(self, min_len=None):
if min_len is None:
self... |
list=[1,2,3,4,5,6,7]
sum=0
for i in range(len(list)):
sum=sum+list[i]
print(sum) |
def find_keyword(word, file):
for i, line in enumerate(file, 1):
if word in line:
print(line)
print("line number:", i,"\n")
def display_topics(file):
for line in file:
if line.startswith("*"):
print(line)
def display_examples(file):
for line in file:
... |
# import requests
# import json
# live_response = requests.get("http://api.postcodes.io/postcodes/cr82hs")
# argument = input("Please enter your postcode ")
#
# url_target = live_response + argument
# print(live_response.content)
# print(type(live_response.content))
# Research how to convert this data into di... |
from collections import defaultdict
import itertools
#why store a huge 2D array when we can just hash everything?
track = defaultdict(itertools.repeat(" ").next)
line_input = raw_input()
#reorder the track so we know we begin in the finish straight
start_index = line_input.find("#")
line_input = line_input[start_index... |
from collections import defaultdict
phone_list = defaultdict(list)
for line in open("students"):
separator_index = line.find(",")
name = line[:separator_index]
key = line[separator_index+1:].strip()
phone_list[key].append(name)
T = int(raw_input())
for test in xrange(1,T+1):
key = raw_input()
names = phon... |
#!/usr/bin/env python3
import argparse
"""
Script to train a grammar based on a set of words for R-loops.
Copyright 2021 Svetlana Poznanovic
"""
def split_word(word):
temp = word.replace('o', '-')
temp = temp.replace('p', '-')
temp = temp.replace('q', '-')
temp = temp.replace('u', '-')
temp =... |
import unittest
import main
class DealToStackTest(unittest.TestCase):
def test_deal_to_stack(self):
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res = main.deal_to_stack(deck)
self.assertEqual(res, [9, 8, 7, 6, 5, 4, 3, 2, 1])
def test_deal_to_empty_stack(self):
deck = []
res = ... |
import collections
import sys
from dataclasses import dataclass
from typing import List, Dict, Optional, Callable
import math
ROOT_NODE = 'COM'
YOU_NODE = 'YOU'
TARGET_NODE = 'SAN'
@dataclass
class Node:
name: str
depth: int
children: List['Node']
parent: 'Node'
# Apply a function to this node a... |
num = int(input('enter a number'))
if num == 0:
print(''' '0'(Zero can never be a prime number as it can be divided by 1, and any other number.
It has an infinite number of divisors and therefore doesn't meet the definition.)''')
elif num == 1:
print(''' A number divisible by only 2 (different) number... |
print("christopher's game")
count = 1
flag = True
while flag:
num = input("a number you want to play with")
guess = int(num)
if guess == 8:
print("you got the number")
flag = False
else:
print("please try another num!")
count += 1
print("it took you " + str(count) + " ti... |
def quick_sort(array: list) -> list:
if len(array) < 2:
return array
else:
pivot: int = array[0]
less: list = [i for i in array[1:] if i <= pivot]
greater: list = [i for i in array[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
def main():
... |
def creaListaLegajos(): #ingresamos nro legajo, nom, apellido y nota hasta ingresar -1
listaLegajos = []
while True:
numeroLegajo = input("Ingrese Numero de Legajo: ")
if numeroLegajo == '-1':
break
nombre = input("Ingrese nombre: ")
apellido = input("Ingrese apellid... |
"""Este modulo ejemplifica el uso de funciones decoradoras"""
def decorarConTexto(funcion):
def funcionInterna(a, b):
print("Primera parte de la decoración. El resultado de la función es: ")
funcion(a,b)
print("Última parte de la decoración. Me despido\n")
return funcionInterna
@decor... |
class humano:
def __init__(self, anios):
self.__piel = "morena" #variable __piel encapsulada no accesible
self.brazos = 2
self.piernas = 2
self.cabeza = 1
self.torso = 1
self.anios_vida = anios
self.salud="ok"
print("U... |
class FilterList:
"""
Maintain list of filters
"""
def __init__(self, filters=[], descs=None):
self.filters = filters
self.descs = descs
def add_filter(self, filter):
"""
:param filter: filter is a filter object or list of filters objects
"""
if isins... |
from random import *
from func_intro import eval
def generate_quiz():
# Hint: Return [x, y, op, result]
x = randint(0, 10)
y = randint(0, 10)
error = randint(-1, 1)
op_list = ["+", "-", "*", "/"]
o = choice(op_list)
s = eval(x, y, o)
r = s + error
return [x, y, o, r]
a, b, op, r = g... |
from random import randint
import pygame
import os
# this dictionary contains the key->color pairs used by the Card constructor
colors = {"0": "r", "1": "b", "2": "g", "3": "y"}
# this dictionary contains the key->color pairs used for the stringification of instances of Card in italian, used for debugging purposes
col... |
import re
catOr = re.search(r'cat|dog', 'The cat is here') ## '|' stands for OR. very versatile
periodWild = re.findall(r'..at', 'The cat in the hat went splat.') ## '.' stands for an arbitrary value/wildcard, spaces mess it up
print(catOr)
print(periodWild)
beginsWith = re.findall(r'^\d', '1 is a number') ##the carr... |
from collections import Counter
mylist = [1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3]
print(Counter(mylist))
mylistLetters = ['a','a',10,10,10]
print(Counter(mylistLetters))
letters = 'aaaaabbbbbbbbbbbccccccccccccdddddddddddd'
c = Counter(letters)
print(c)
d = {'a' : 10}
print(d)
print(d['a']) |
## print(list(range(0,10)))
## ^(range) is a basic generator
## def create_cubes(n):
## result = []
## for x in range(n):
## result.append(x**3)
## return result
def gen_fibon(n):
a=1
b=1
for i in range(n):
yield a
a,b = b,a+b
def create_cubes(n):
for x in range(n):
... |
def partition(arr,l,h):
i=l-1
p=h
for j in range(l,h):
if(arr[j]<=arr[p]):
i+=1
arr[i],arr[j]=arr[j],arr[i]
arr[i+1],arr[h]=arr[h],arr[i+1]
return (i+1)
def quicksort(arr,l,h):
if(l<h):
pi=partition(arr,l,h) #placing pivot element in its corr... |
from solution import Solution
def test_is_a_palindrome():
"""
Test that it can identify valid palindrome
"""
solution = Solution()
string = "A man, a plan, a canal: Panama"
expected = True
result = solution.isPalindrome(string)
assert result == expected
string = "a."
expec... |
'''
Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is no... |
"""
programe goals:
3. pull the values stored at specific indexes
4. conver input to INTs
5. put all action in a while loop
6.add exit option
"""
import random
myList = []
uniqu_list = []
def mainProgram():
#build our while loop
while True:
print("Hello, there! Let's work with lists!")
... |
import pymongo
from pymongo import MongoClient
# connect to host
client = MongoClient('localhost', 27017)
# connect to database myFirstE
db = client.myFirstE
# connect to collection
stud1 = db.stud
# print('connection made successfully')
#
# # inserting a document
# post = {"author": "Mike", "text": "my first blog"... |
#!/usr/bin/python
from collections import defaultdict
from typing import Dict
from delete_comments import delete_comments
# Count how many times a castling move was picked (O-O = kingside, O-O-O = queenside)
def delete_checkmarks(move: str) -> str:
return move.replace("+", "").replace("#", "")
def count_castl... |
a = [1,1,2,3,4,8,13,21,34,55,89]
#now run a loop to traverse through the list
def print_less_than_five():
for i in range(len(a)):
if a[i]<5: #checking if the element is less than 5
print(a[i]) #printing
"""
or we cound write this like
for i in a:
if i<5:
print(i)
"""
print_less_than_five() |
'''
Created on Mar 7, 2015
For a given integer N, this prints all possible permutations of fully balanced parentheses.
Example: 3
()
(()) ()()
((())) (()()) (())() ()(()) ()()()
@author: Vinodh Periyasamy
'''
def brackets(N):
for i in range(1,N+1):
brackets_internal("", 0 , 0 , i)
de... |
#------------------------------------------------------------------------------#
# Let's learn about list comprehensions! You are given three integers x, y and z
# representing the dimensions of a cuboid along with an integer n. You have to
# print a list of all possible coordinates given by on a 3D grid where the sum
... |
#------------------------------------------------------------------------------#
# You are given a positive integer N. Print a numerical triangle of height N - 1
# like the one below:
# 1
# 22
# 333
# 4444
# 55555
# ......
# Can you do it using only arithmetic operations, a single for loop and
# print statement?
# Use ... |
#------------------------------------------------------------------------------#
# Read two integers and print two lines. The first line should contain integer
# division, // . The second line should contain float division, / .
# You don't need to perform any rounding or formatting operations.
#------------------------... |
def FileAndString(fname,s):
with open(fname,"r") as F:
for line in F.readlines():
if s in line:
print('String', s, 'Found In Line', line)
return True
else:
print("string", s, "not found")
return False
... |
'''
This script will check if the time period specified is acceptable and then adjust
the timeframe.
Input: timeframe (string)
Output: timeframe (string)
'''
import datetime
from datetime import date, timedelta
def Check_dates(timeframe):
# Check if the date is within 3 days from current date
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 15:57:50 2019
@author: Neo
"""
##############################################
#### inheritance
# parent class
class Dog:
# class attriute
species = 'mammal'
# initializer
def __init__(self, name, age):
self.name ... |
lar = float(input('Qual a largura da sua parede? '))
alt = float(input('Qual a Altura da sua parede? '))
metrosq = alt * lar
litros_tinta = metrosq / 2
print('Sua parede tem {}m de largura, {}m de altura e a área é {}m2 \nVocê vai precisar de {} litros de tinta para pintar sua parede'.format(lar, alt, metrosq, litro... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def f(x,y):
return (x**2+x*y-10)
def g(x,y):
return (y+3*x*y**2-57)
def fx(x,y):
return (2*x+y)
def fy(x,y):
return (x)
def gx(x,y):
return (3*y**2)
def gy(x, y):
return (1+6*x*y)
xi = float(input("x için başlangıç değerini girin: "))
yi ... |
import scipy as sp
# matrix A, stored as array
array_A = sp.array([
[1, 2],
[0, 3]
])
# matrix B, stored as array
array_B = sp.array([
[-1, 0],
[-2, 1]
])
# vector V, stored as array
array_V = sp.array([
[1],
[2]
])
# the same matrix A, stored as matrix
matrix_A = sp.matrix([
[1, 2],
... |
__author__ = 'ferrard'
import math
def heart(r):
"""Prints a heart with size parametrized by r (must be an even number)"""
if r % 2 != 0:
print("r must be even")
return
for y in range(r*2 + 1 - r//2):
for x in range(r*2 + 1):
# top two half-circles
if y <= ... |
# mind that this program thinks that you where born at 00:00:00
# this app is based on the Gregorian calender
sal_tavalod= int(input("sal tavalod khod ra vared konid"))
mah_tavalod= int(input('mah tavalod khod ra vared konid'))
roz_tavalod= int(input("roz tavalod khod ra vared konid "))
import datetime
date_and_... |
import random
from item import Item
#GLOBAL VARIABLES
# Generates 0-30 random items with value = 0-30 and weight = 0-30
ITEMS = [Item(random.randint(0,30),random.randint(0,30)) for x in range (0,30)]
# Capacity of the knapsack randomized according to number of items
CAPACITY =10*len(ITEMS)
# Size of initia... |
def create_drug_list(drugDict):
"""
This function receives the dictionary as input and creates a list of tuples. Each tuple contains drug name,
total cost of the drug, and number of unique prescibers for that drug. It, then, sorts the list based on the
total cost.
"""
output_data = list()
fo... |
#name = raw_input("What is your name? ")
#print "Hello", name
hrs = float(raw_input("hrs? "))
rate = float(raw_input("rate? "))
print hrs, rate
pay = hrs*rate
print pay |
fruit = 'banana'
letter = fruit[1]
print letter
# a character too far
# len will tell us the length of the string. and not the length - 1
# you can loop through strings
fruit = 'bamama'
index = 0
while index < len(fruit):
leter = fruit[index]
print index, letter
index = index + 1
# it can also be done in a loo... |
MULTI-TABLE RELATIONAL SQL
Data models and relational sqlite
\Lecture 1 Designing a Data Model
# we make a Schema and contract, and than there are a lot of tables and some columns and some connections.
# Connections are what make this powerful.
# RULES;
# 1 - Don't put the smae string data in twice - use a relation... |
# 4.6 Write a program to prompt the user for hours and rate per hour using raw_input to compute gross pay. Award time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of time-and-a-half in a function called computepay() and use the function to do the computation. T... |
r = float(input())
a = 3.14159*r*r
print("A=%0.4f"%a) |
def fact(n):
soma = 1
for i in range(n,0,-1):
soma*=i
print(soma)
n = int(input())
fact(n) |
def contar_substr(string,substring,pos):
cont = 0
inicio = 0
while inicio <= pos:
tem_na_pos = string.find(substring, inicio)
if tem_na_pos != -1:
inicio = tem_na_pos + 1
cont += 1
else:
return cont
i = 1
while(True):
try:
... |
l = int(input())
op = input()
soma = 0
for i in range(12):
for j in range(12):
x = float(input())
if i == l:
soma+=x
if op == "S":
print("%.1f"%soma)
else:
print("%.1f"%(soma/12)) |
def sqrt(n):
if n==0:
return 0
else:
n-=1
return 1/(2+sqrt(n))
n = int(input())
print("%.10f" %(1+sqrt(n))) |
n = int(input())
# É obrigado ser lido um int, n sei pq
n = str(n)
n = list(n)
n.reverse()
print("".join(n)) |
x = int(input())
y = int(input())
menor = min(x,y)
maior = max(x,y)
for i in range(menor+1,maior):
if i%5==2 or i%5==3:
print(i) |
#!/bin/python3
import sys
n = int(input().strip())
unsorted = []
unsorted_i = 0
for unsorted_i in range(n):
unsorted_t = str(input().strip())
unsorted.append(int(unsorted_t))
# your code goes here
unsorted.sort()
for i in unsorted:
print(i)
|
#!/bin/python3
import sys
s = input().strip()
count = 1
for char in s:
if ord(char) < 97:
count += 1
print(count)
|
def fib (num):
if num <= 2:
return 1
return fib(num-1) + fib(num-2)
num = int(input("Ingrese n: "))
print (fib(num)) |
from collections import deque
def es_palindromo (frase):
pila = list(frase)
cola = deque([pila])
for i in range(len(frase)):
if pila.pop() != cola.popleft():
return False
return True
|
ch=raw_input("enter the charecter")
if(ch=="a"):
print("ch is a vowel")
elif(ch=="e"):
print("ch is a vowel")
elif(ch=="i"):
print("ch is a vowel")
elif(ch=="o"):
print("ch is a vowel")
elif(ch=="u"):
print("ch is an vowel")
else:
print("ch is a consonent")
|
'''
Question: String shift
We define that a new string function, named shift:
shift('ABCD', 0) = "ABCD"
shift('ABCD', 1) = "BCDA"
shift('ABCD', 2) = "CDAB"
In other words, this function is used to cut left n characters of the string
and move them to the right. When giving a n-long stri... |
'''13) (Python.org.br) João Papo-de-Pescador, homem de bem, comprou um microcomputador
para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes
maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve
pagar uma multa de R$ 4,00 por quilo excedente. Jo... |
nota1=float(input("Digite a nota do 1 bimestre:"))
nota2=float(input("Digite a nota do 2 bimestre:"))
nota3=float(input("Digite a nota do 3 bimestre:"))
nota4=float(input("Digite a nota do 4 bimestre:"))
print((nota1+nota2+nota3+nota4)/4)
|
import re
def is_leap_year(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
# date = "2020-08-19"
def cal_day(date):
if re.match(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", date) == None:
return None
date = date.split("-")
year = int(date[0])
month = int(date[1])
day = int(date... |
"""
*
**
***
****
*****
"""
for i in range(6):
for _ in range(i):
print("*", end="")
print()
"""
*
**
***
****
*****
"""
for i in range(6):
for _ in range(5 - i):
print(" ", end="")
for _ in range(i):
print("*", end="")
print()
"""
*
***
*****
*******
**... |
def sum(list1):
list1.sort()
return list1[-1], list1[-2]
def main():
list1 = [1, 2, 3, 4, 5, 6]
list1 = [8, 2, 1, 6, 7, 5]
s1, s2 = sum(list1)
print(s1, s2)
if __name__ == "__main__":
main()
|
def pvsr(x):
print(4)
print(3)
print(2)
return x
print (pvsr(1))
y = pvsr(1) # store only return (1)
print(y)
list = [14, 24, 14, 230, 100]
def fun(list):
i = 0;
while i < len(list):
list[i] = (list[i] + 10) // 2 # Python 3 // for division and see integers, instead of floats
... |
from random import randint
import itertools
def playMontyHall(switchDoor) :
#Number of doors :
numberofDoors = 3
verbose = 1
if verbose :
print "---------------- STARTING GAME ----------------"
# We have 3 doors (0,1,2), with goats behind two of them and a car behind the other one :
carPosition = randint(0,num... |
class Condicion:
def __init__(self, num1, num2):
self.numero1=num1
self.numero2=num2
numero = self.numero1+self.numero2
self.numero3=numero
def condicion(self):
if self.numero1==self.numero2:
print("numero1:{} y numero2 {} son iguales".... |
'''Write a program in Python which uses a while loop to sum the squares of integers
(starting from 1) until the total exceeds 200.
Print the final total and the last number to be squared and added.'''
i = 0 # Initialize iterator variable
total = int(input('Enter the value you would like to exceed\n'))
for squar... |
'''This code takes in a date in string format, converts to a datetime object, and then outputs the date
formatted as weekday, day/month/year'''
import datetime
monthsUpper = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8,
"September": 9, "Oct... |
#to calculate wieghted score of student
as1 = int(input("Enter The score in Assignment1:"))
as2 = int(input("Enter The score in Assignment2:"))
as3 = int(input("Enter The score in Assignment3:"))
e1 = int(input("Enter The score in Exam1:"))
e2 = int(input("Enter The score in Exam2:"))
ws = ( as1 + as2 + as3 ) *0.... |
#to style the string
str1 = input("Enter the String:")
print("To lowercase:",str.lower(str1))
print("To uppercase:",str.upper(str1))
print("To camelcase:",str.title(str1)) |
"""
Code Challenge
Name:
weeks
Filename:
weeks.py
Problem Statement:
Write a program that adds missing days to existing tuple of days
Input:
('Monday', 'Wednesday', 'Thursday', 'Saturday')
Output:
('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
"""
list1=... |
print("----------嵌套----------")
# 字典alien_0包含一个外星人的各种信息,但无法存储第二个外星人的信息,
# 创建外星人列表,方便管理,每个外星人都是一个字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
print("\n-----... |
# 标识符:
# 以单下划线开头(_foo)代表不能直接访问的类属性,需要通过类提供的接口进行访问,
# 不能用 "from xxx import *" 导入。
# 以双下划线开头的(__foo)代表类的私有成员。j
# 以双下划线开头和结尾的(__foo__)代表特殊方法专用的标识,如 __init__() 代表
# 类的构造函数。
# Python 使用缩进来实现代码分组
# 缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量
# 算术运算符: + - * / % ** //
# 比较运算符: == != > < >= <=
# 逻辑运算符: and or not
# 成员运算符: in 和 not in
... |
import json
print("----------喜欢的数字----------")
# 编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个
# 数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息
# "I know your favorite number! It's "。
favorite_num = input("Please enter your favorite number: ")
filename = 'datadir/favorite_number.json'
with open(filename, 'w') as f_obj:
json.dump(favo... |
# 城市和国家
# 编写一个函数,它接受两个形参: 一个城市名和一个国家名。这个函数返回一个
# 格式为City,Country的字符串,如Santiage,Chile。将这个函数存储在一个名
# 为city_functions.py的模块中。
# 创建一个名为test_cites.py的程序,对刚编写的函数进行测试(别忘了,你需要导
# 入模块unittest以及要测试的函数)。编写一个名为test_city_country()的方法,
# 核实使用类似于'santiage'和'chile'这样的值来调用前述函数时,得到的字符串
# 是正确的。运行test_cites.py,确认测试test_city_country()通过了。
... |
print("----------词汇表----------")
# Python字典可以模拟现实生活中的字典,为避免混淆,将后者称为词汇表
glossaries = {
'字典': '一系列键-值对',
'条件测试': '值为True或False的表达式',
'列表': '一系列按特定顺序排列的元素组成',
'元组': '不可变的列表,一系列按特定顺序排列的元素',
'切片': '对象的子集,处理对象(列表、元组)的部分元素',
}
print("字典: " + glossaries['字典'])
print("条件测试: " + glossaries['条件测试'])
print("列... |
import os
print("----------创建存放数据的目录----------")
def create_path(path):
"""创建目录文件夹"""
is_exist = os.path.exists(path)
# 如果路径不存在,则创建
if not is_exist:
os.mkdir(path)
create_path('datadir')
|
import numpy as np
print("----------矩阵合并----------")
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
# hstack()、vstack()参数要使用列表或元组传入
# 矩阵横向合并
print(np.hstack([arr1, arr2]), '\n')
# 矩阵纵向合并
print(np.vstack((arr1, arr2)))
"""
>>> Execution Result:
----------矩阵合并----------
[[1 2 5 6]
[3 4 7 8]]
... |
# 集合的基本功能: 关系测试和删除重复元素
# 使用 {} 创建集合
# 注意: 要创建空集合必须使用 set() 函数,单独使用 {} 创建的是空字典
# 删除重复元素
basket = {'a', 'b', 'a', 'b', 'c', 'c'}
print(basket, '\n')
# 检测集合的成员
print('a' in basket)
print('d' in basket, '\n')
# 集合操作
a = set('abracadabra')
b = set('alacazam')
print(a)
print(b)
# a - b: 在 a集合中,但不在 b 集合中
print(a - b)
# a ... |
# 私有属性和方法
# 1. 在类的内部可以定义属性和方法,在方法内封装业务逻辑,通过类的对象访问方法。
# 但类的属性既可以在类的内部进行访问和修改,也可以通过类的对象进行访问和修改,
# 这样会破坏数据的封装。
# 2. 如果要让类的属性不能被外部访问,可以在属性的名称前加上两个下划线“__”。
# 3. 如果属性的名称以两个下划线开头,则表示是私有属性。
# 4. 私有属性在类的外部不能直接访问,需要通过调用对象的共有方法来访问。
# 5. 子类可以继承父类的公有成员,但是不能继承其私有成员。
# 6. 私有方法的名称以两个下划线开始,在私有方法中可以访问类的所有属性,只能
# 在类的内部调用私有方法,无法通过对象调用私有方法... |
print("----------传递任意数量的实参----------")
# 有时候,预先不知道函数需要接受多少个实参,Python允许函数从调用语句
# 中收集任意数量的实参。
# 比如,制作一个比萨,它需要接受很多配料,但无法预先确定顾客要多少种配料
# 形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将
# 接收到的所有值都封装到这个元组中。
def make_pizza1(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
# Python将实参封装到一个元组中,即便函数只能收到一个值也如此
make_pi... |
# 复制前面的程序user_profile.py,在其中调用build_profile()来创建有关
# 你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。
def user_profile(first, last, **infos):
"""整洁打印名字及相关描述信息"""
profile = {}
profile['first name'] = first
profile['last name'] = last
for k, v in infos.items():
profile[k] = v
return profile
myinfo ... |
print("----------电影票----------")
# 有家电影院根据观众的年龄收取不同的票价: 不到3岁的观众免费;
# 3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,
# 在其中询问用户的年龄,并指出其票价。
prompt = input("How old are you? ")
age = int(prompt)
while True:
if age < 3:
print("Younger than 3 years old, no tickets are require.")
continue
elif age <= 12:
... |
# 异常的分类处理
# 如果想同时使用 Exception 和单个类型异常捕捉,应该把单个类型异常的捕捉放
# 到 Exception 的前面,因为如果把 Exception 作为捕获的第一个异常,那么使用
# Exception 会捕捉所有的异常错误,Exception 下面的单个异常处理就不再执行。
try:
x = int(input("input x: "))
y = int(input("input y: "))
print("x/y = ", x/y)
# 捕捉除0异常
except ZeroDivisionError:
print("ZeroDivison")
# 捕捉多个异常
exce... |
print("----------处理FileNotFoundError异常----------")
# 使用文件时,一种常见的问题是找不到文件
# filename = 'alice.txt'
# with open(filename) as f_obj:
# contents = f_obj.read()
# ----------处理FileNotFoundError异常----------
# Traceback (most recent call last):
# File "e11_alice.py", line 6, in <module>
# with open(filename) as f_obj:
# Fi... |
# 修改前面的函数,使其包含第三个必不可少的形参population,并返回一个格式为
# City,Country - population xxx 的字符串,如Santiage,Chile - population
# 5000000。运行test_cities.py,确认测试test_city_country()未通过。
# 修改上述函数,将形参population设置为可选的。再次运行test_cities.py,确认
# 测试test_city_country()又通过了。
# 再编写一个名为test_city_country_population()的测试,核实可以使用类似于
# 'santiage'、'chile'和'... |
# 用队列实现斐波那契数列
count = 10
a, b = 1, 1
ls = []
for i in range(count):
ls.append(a)
a, b = b, a + b
print(ls)
# >>> Execution Result:
# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
|
# 魔法方法和特殊属性
# 魔法方法也称特殊方法,总是被双下划线包围,如 __init__,特殊属性也是
# 以双下划线包围的属性,如 __dict__ 和 __slots__。
# __dict__ 可以访问类的所有属性,以字典的形式返回
class People(object):
# 定义构造方法
def __init__(self, name, age):
# 初始化类的实例属性
self.name = name
self.age = age
people = People('Joe', 22)
print(people.__dict__)
print("na... |
class Solution:
"""
@see https://oj.leetcode.com/problems/multiply-strings/
"""
# @param num1, a string
# @param num2, a string
# @return a string
def multiply(self, num1, num2):
#return str(int(num1)*int(num2))
list1 = []
list2 = []
for i in num1:
... |
class Solution:
# @param num, a list of integer
# @return a list of lists of integer
def subsetsWithDup(self, S):
res = [[]]
S = sorted(S)
for n in S:
for item in res[0:]:
t = item[0:]
t.append(n)
if t not in res:
... |
import collections
class Solution:
"""
@see https://oj.leetcode.com/problems/valid-parentheses/
"""
# @return a boolean
def isValid(self, s):
q = collections.deque()
for c in s:
if len(q) > 0:
c1 = q.pop()
if (c1=="(" and c!=")... |
class Solution:
"""
@see https://oj.leetcode.com/problems/anagrams/
"""
# @param strs, a list of strings
# @return a list of strings
def anagrams(self, strs):
d = {}
for str in strs:
str1 = sorted(str)
str1 = "".join(str1)
if str1 no... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
s = ''
node = self
while node:
if s == '':
s = str(node.val)
else:
s += '->' ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
"""
@see https://oj.leetcode.com/problems/swap-nodes-in-pairs/
"""
# @param a ListNode
# @return a ListNode
def swapPairs(self, head)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.