text stringlengths 37 1.41M |
|---|
""""
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
"""
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right... |
import pygame
# Game config
WIDTH = 600
HEIGHT = 600
FPS = 1
SCORE = 0
clock = pygame.time.Clock()
red = (161, 40, 48)
lime = (0, 255, 0)
snake_body = []
x_back = 30
y_back = 30
intro_screen = False
class Player:
def __init__(self, x, y, width, height, direction):
self.x = x
self.y = y
sel... |
#!/usr/bin/env python
'''Re-encryption demonstration
This little program shows how to re-encrypt crypto from versions older than 2.0.
Those versions were inherently insecure, and version 2.0 solves those
insecurities. This did result in a different crypto format, so it's not backward
compatible. Use this program as a... |
# import json
# alltweets = []
# def get_all_tweets(name, screen_name):
# #Twitter only allows access to a users most recent 3240 tweets with this method
# #authorize twitter, initialize tweepy
# # auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# # auth.set_access_token(access_key, acce... |
"""
Links the values of array in "x", "y" or "z" direction.
Example:
Arrays sent: |---o---|---o---|---o---|---o---|---o---|---o---|
0 1 2 3 4 5
Returnig: |---o---|---o---|---o---|---o---|---o---|---o---|
(0+5)/2 1 2 3 ... |
# Реализовать структуру «Рейтинг», представляющую собой убывающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга.
# Если в рейтинге существуют элементы с одинаковыми значениями,
# то новый элемент с тем же значением должен разместиться после них.
# Подсказка. Например, набор нат... |
# Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
def int_func(a):
return str.title(a)
print(int_func(a = input('Insert lowercase text -> '))) |
def f(n):
if n == 1:
return 1
return n * f(n-1)
r = f(7)
print(r)
# 1 1 2 3 5 8 13 21 34
def fibonacci(n):
if n == 2:
return 2
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
k = fibonacci(10)
print(k) |
import random
import math
class Array():
def __init__(self, n):
self.n = n
self.arr = self.generate_arr()
def generate_arr(self):
arr = []
n = self.n
for i in range(n):
a = random.randint(10, 100)
arr.append(a)
return arr
def ex231(... |
def replace_words(text, word_dic):
"""
replace words in text via a dictionary
>>> text = 'A Colorful day in city Center.'
>>> word_dic = {'Color': 'color', 'Center': 'sub'}
>>> replace_words(text, word_dic)
'A colorful day in city sub.'
"""
import re
yo = re.compile('|'.join(map(re.... |
from tkinter import *
from tkinter import ttk
root = Tk()
lbl = ttk.Label(root, text="Starting...")
lbl.grid()
lbl.bind('<Enter>', lambda e: lbl.configure(text='Moved mouse inside'))
lbl.bind('<Leave>', lambda e: lbl.configure(text='Moved mouse outside'))
lbl.bind('<1>', lambda e: lbl.configure(text='Clicked left mo... |
from tkinter import *
from tkinter import ttk
# to use jpg image
from PIL import Image, ImageTk
root = Tk()
# Frame
frame = ttk.Frame(root)
frame.grid()
frame['padding'] = (5,10)
frame['borderwidth'] = 2
frame['relief'] = 'raised' # 'sunken'
# Label
label = ttk.Label(frame, text="full name:")
label.grid()
resultsCo... |
from math import sqrt
from data import *
class Vector2:
def __init__(self, x, y):
self.x = x
self.y = y
def tuple(self):
return self.x, self.y
def normalized(self):
return Vector2(self.x / self.distance(), self.y/self.distance())
def __iter__(self):
return s... |
# Zachary Tarell - zjt170000
# Homework 1: Search Algorithms - 8 puzzle
# CS 4365.501 Artificial Intelligence
import sys
from collections import deque
from heapq import heappush, heappop, heapify
class State:
def __init__(self, state, parent, move, depth, cost, key):
self.state = state
... |
#!/usr/bin/python3
def no_c(my_string):
new_string = ""
for i in my_string:
if i is "c" or i is "C":
continue
new_string = new_string + i
return new_string
|
"""Unittest for class Square
"""
import unittest
import sys
import io
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
class TestSquareClass(unittest.TestCase):
def test_is_subclass(self):
"""test Square is subclass of Base or not"""
r = Square(... |
import numpy as np
import random
class NeuralNet:
def __init__(self, structure, learning_rate):
"""
Initialize the Neural Network.
- structure is a dictionary with the following keys defined:
num_inputs
num_outputs
num_hidden
- learning rate is a float that should be used as ... |
# imports
from maze import *
from sys import *
import pygame
from math import floor
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
INVO = (210,103,40)
class MazeView:
"""
Provide some functions to visualise the result of the maze generator
"""
#--------------------... |
class Pizza():
def __init__(self,tipo):
self.ingredientes = ["Mozzarella","Tomate"]
self.tipo = tipo
def seleccion(self):
pass
def agregar(self,agregado):
self.agregado = agregado
self.ingredientes.append(self.agregado)
def mostrar(self):
... |
""" Ejercicio 6 Escribir un programa que pida al usuario un número
entero y muestre por pantalla si es un número primo o no. """
def primo(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def start():
... |
""" Ejercicio 13
Generar 10 números aleatorios, mostrarlos por pantalla y mostrar el promedio.
"""
from random import randint
promedio = 0
for i in range(10):
numero = randint(0,10)
print(numero)
promedio = promedio + numero
print(promedio/10)
|
class Alumno():
def __init__(self,sexo,nombre):
self.sexo = sexo
self.nombre = nombre
def separar(self):
if (self.sexo == "M" and self.nombre[0]<= "M") or (self.sexo == "H" and self.nombre[0]>= "N"):
print("Pertenece al Grupo A")
else:
... |
""" Ejercicio 18
Modificar el programa del ejercicio 17 agregando un control de datos vacíos.
Si por algún motivo alguno de los datos viene vacío o igual a "" debemos generar una
excepción indicando que ocurrió un problema con la fuente de datos y notificar por pantalla.
La excepción debe ser una excepción propia.
... |
from decimal import *
class Value:
def bellardBig(self,n):
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(-1)**k/(1024**k))*( Decimal(256)/(10*k+1) + Decimal(1)/(10*k+9) - Decimal(64)/(10*k+3) - Decimal(32)/(4*k+1) - Decimal(4)/(10*k+5) - Decimal(4)/(10*k+7) -Decimal(1)/(4*k+... |
# Rename Images with Date Photo Taken
# Purpose: Renames image files in a folder based on date photo taken from EXIF metadata
# Author: Matthew Renze
# Update: Clement Changeur
# Usage: python rename.py input-folder
# - input-folder = (optional) the directory containing the image files to be renamed
# E... |
"""Function to run if the user wants to send a thank you note."""
import os
import sys
def clear_screen():
"""Taken from the Treehouse shopping_list exercise."""
os.system("cls" if os.name == "nt" else "clear")
donors_info = {
'Sam Wippy': [100000],
'Willy Wonka': [12, 13, 14],
'Garth Brooks': [... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# 总资产
asset_all = 0
li = input("请输入总资产:")
asset_all = int(li)
goods = [
{"name":"电脑","price":1999},
{"name":"鼠标","price":10},
{"name":"游艇","price":20},
{"name":"美女","price":998},
]
for i in goods:
# {"name":"电脑","price":1998}
print(i["name"],i["pric... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# li = ["alex","eric"] # 列表
# li = ("alex","eric") # 元祖
# s = "_".join(li) # .join 把字符串链接起来
# print(s)
# s = "alex"
# # news = s.lstrip() # 移除左边空白‘
# news = s.rstrip() # 移除右边空白
# news = s.strip() # 移除两边空白
# print(news)
# s = "alex SB alex... |
# -*- coding:utf-8 -*-
print('hello,python')
print('hello,'+'python')
temp = '你是我的小苹果'
temp_unicode = temp.decode('utf-8')
temp_gbk = temp_unicode.encode("gbk")
print(temp_gbk) |
# %% [markdown]
# **コンプリヘンション(comprehension)**<br>
# **リスト内包表記**<br>
# **[式 for 変数 in リスト if 条件]**<br>
# In[]:
sample_list1 = ['a', 'b', 'c', 'd', 'e']
print(sample_list1)
sample_list2 = [i*3 for i in sample_list1 if i >= 'c']
print(sample_list2)
# %% [markdown]
# **ディクショナリ内包表記**<br>
# **{式 : 式 for 変数 in リスト if 条件}**... |
# import libraries
import sys
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
"""
Load the files, read the messages and categories files and merge both dataframe .
Return the dataframe with messages and the categories of ea... |
#Entrada de Dados:
#Digite a primeira nota: 4
#Digite a segunda nota: 5
#Digite a terceira nota: 6
#Digite a quarta nota: 7
#Saída de Dados:
#A média aritmética é 5.5
nota1 = input("Digite a primeira nota")
nota2 = input("Digite a segunda nota")
nota3 = input("Digite a terceira nota")
nota4 = input("Digite a quart... |
#Receba um número inteiro na entrada e imprima
#par
#quando o número for par ou
#ímpar
#quando o número for ímpar.
numero = int(input("Digite seu número: "))
numero = numero%2
if (numero == 0):
print('Par')
else:
print('Ímpar')
|
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
df = pd.read_csv('train.csv')
"""
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(df,df['SalePrice'],test_size=0.1,random_state=0)
"""
#Since we have a separate test data ... |
# Mario Fernández
# Exercise 1
# Si se quieren modificar los valores, más abajo en el main se pueden cambiar
def RGB_TO_YUV(R, G, B):
# Implementar las líneas que están presentes en la teoría (diapo 46)
Y = 0.257 * R + 0.504 * G + 0.098 * B + 16
U = -0.148 * R - 0.291 * G + 0.439 * B + 128
V ... |
# Heap Practice Module
# Dec 15 2020
# 11 Jan 2021
# TODO
def array_to_heap(arr):
'''
returns a heap data structure
'''
pass
# MIN HEAP
# COMPLETE binary tree where each node is SMALLER than its children
# root is minimum element in tree
# Key Operations:
# insert O(logn)
... |
indices = dict()
def preorder(inorder:list, postorder:list, shift=0) -> list:
if inorder == [] or postorder == []: return []
# get last element (our root) from postorder
root = postorder.pop()
# find its index in inorder
idx = indices[root] - shift
# elements before and after
before_root... |
# # #####################
# # ps1a
# # PSET 1A
# # #####################
#inputs
annual_salary = float(input("Annual salary: "))
portion_saved = float(input("Monthly portion saved: "))
total_cost = float(input("Cost of your dream home: "))
#knowns
portion_down_payment = 0.25
current_savings = 0
monthly_salary = annua... |
# HAAR CASCASE METHOD:
# feature based machine learning
# uses pretrained images of labeled poitives and negatives
# runs through thousands of classifiers in a cascaded manner
# Use cases: detecting faces
import numpy as np
import cv2
img = cv2.imread("Detection/assets/faces.jpg")
gray = cv2.cvtColor(img, cv2.COLOR... |
def keyword_generate(inputt):
string = str(inputt)
res = ''
for char in string:
res += chr(int(char))
return res
def dhke1(t,p,m,a,message_in, encrypt):
if encrypt:
# generate the key with your a:
num_key = int(pow(m,a,p))
# get the keyword
keyword = keyw... |
'''
Tutorial 2: Image Fundamentals and Manipulation
Piero Orderique
15 Feb 2021
'''
import cv2
from random import randint
#* openCV loads in image as numpy array!
img = cv2.imread('Detection/assets/MIT_Dome.jpg', -1)
#* h, w, channels --- pic is actually rep by 3D array in BGR (NOT RGB)
print(img.shape)
'''
[
r... |
# Graph Searching Algorithms
# Piero Orderique
# 11 Jan 2021
# SIDE_NOTE:
# fixed login authentication error with git by running: git config --global credential.helper winstore
# from https://stackoverflow.com/questions/11693074/git-credential-cache-is-not-a-git-command
# Structures - adjacency list implement... |
########## un ordered collection of unique elements ##########
##### sets are mutable #####
set1 = {1, 2, 3 , 4 , 4 }
print(set1)
set1.add(5)
print(set1)
###### union(), intersection(), difference(), symmetric difference()
set2 = {2,5,3,5,3,1,7,8}
print(set1.union(set2)) #all unique values from both sets
print(s... |
#pass variable to script
from sys import argv
script, filename = argv
#call a function on txt to open (filename)
txt = open(filename)
print "Here's your file %r: " %filename
#give command to file by using dot .
print txt.read() #Hey txt, do your read command with no parameter!
txt.close()
file_again = raw_input ... |
#f(0) = 0
#f(1) = 1
#f(n) = f(n-1) + f(n-2)
def f(n):
sum = (n-1) + (n - 2)
sentence = """
For F({}) = f({}-1)+ f({}-2) is {}
""".format(n,n,n, sum)
print sentence
def main():
print """
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)
Find f(n) """
a = int(raw_input("Enter an in... |
"""
Logic operations for combining objects that represent named statements, to improve readability.
Named statements are represented as name/statement pairs in a dict.
Because conjunction is more common, it is represented my merging dicts.
Disjunction is represented by a list instead.
E.x.:
>>> a = Name(a, "A")
{"A":... |
#-------------------------------------------------------------------------------
# Name: harmonograph
# Purpose:
#
# Author: Adam & Matthew
#
# Created: 12/11/2016
# Copyright: (c) Adam & Matthew 2016
#-------------------------------------------------------------------------------
import turtle as g... |
//sort()method -permanently
letter=['b','a','d','e','g','f']
print(letter)
['b','a','d','e','g','f']
letter.sort ()
print(letter)
['a','b','d','e','f','g']
letter.sort(reverse=true)
print(letter)
['g','f','e','d','b','a']
print(letter)
['g','f','e','d','b','a']
//sorted()Function-temporary
letter=['b','a',''d','e','g'... |
#-----------------------------------------------------------------------------#
# Title: CDInventory.py
# Desc: Script for Assignment 05, managing a CD inventory.
# Change Log: (Who, When, What)
# Jurg Huerlimann 2020-Aug-07, Created File from CDInventory_Starter.py script.
# Jurg Huerlimann 2020-Aug-08 Changed fu... |
# Choose your own adventure game - Individual Python Projects --- 19th Dec 2020
import random
import time
def displayIntro():
print('\nYour car broke down in your drive through the desert 2 days ago.')
time.sleep(2)
print('You have been walking across the sand dunes for what feels like forever with no ro... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 28 17:49:46 2020
@author: Zaki
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs #to create our dataset
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
#def... |
# Python to Json
data = {
'name': 'Gopinath Jayakumar',
'Exp': '10+',
'value': None,
'is_nothing': True,
'hobbies': ('always sleeping....', 'always sleeping....')
}
import json
# dumps: Convert python data to json
print(type(data))
data = json.dumps(data, indent=4)
print(data)
# dump: write the ... |
import os
import csv
from typing import Counter
csvpath = os.path.join('Resources','election_data.csv')
Votes = []
Candidates = []
percent_votes = []
total_votes = 0
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_Header = next(csvfile)
for row in csvreader:
... |
# get input
with open('Day15/input.txt', 'r') as f:
initNums = [int(x) for x in f.readline().split(',')]
# return the number said on that turn
def numberSaid(turnNum: int):
# first n numbers said
said = {k:v for v,k in enumerate(initNums, 1)}
nextnum = 0
turn = len(initNums) + 1
# iterate until... |
# required fields
fields = [
'byr',
'iyr',
'eyr',
'hgt',
'hcl',
'ecl',
'pid'
# 'cid'
]
# passport extends dictionary with a custom isValid function
class Passport(dict):
def isValid(self):
# check if all fields exist
for field in fields:
if field not in s... |
user1_name = input('User1, what is your name?')
print('')
print('Welcome {}'.format(user1_name))
print('')
user2_name = input('User2, what is your name?')
print('Welcome {}'.format(user2_name))
print('')
# Доска
board = [
[1,2,3],
[4,5,6],
[7,8,9]
]
board_image = [
['1','2','3'],
['4','5','6'],
... |
def max(i_list: list) -> int:
"""
Compute the max of a list
:param i_list: The source list
:return: The maximum of the list
"""
max = i_list[0]
for element in i_list[1:]:
if element>max:
max=element
return max
if __name__ == "__main__":
print(max([4,5,6,3,4,9,10,... |
def palindrome(word: str) -> bool:
"""
Check if a string is palindrome
:param word: the word to analyze
:return: True if the statement is verified, False otherwise
"""
i=0
while i < int((len(word)+1)/2):
if word[i] != word[-(i+1)]: return False
i+=1
return True
if __name... |
# define a function which given a binary search tree
# T of integers and a rectangular matrix M
# of integers verify if there exists an ordered row of
# M (e.g. values in ascending order) whose
# values are in T.
class Node:
def __init__(self, value, left=None, right=None):
self.left = left
self.ri... |
def insert(value: int, in_list: list) -> list:
"""
Insert a value in an ordered list
:param value: value to insert
:param in_list: list where we add the value
:return: the new list
"""
for idx in range(len(in_list)):
if in_list[idx] >= value:
return in_list[:idx] + [value... |
def duplicate(i_list: list,n)-> list:
"""
Duplicate each element of the list
:param i_list: The source list
:param n: The number of repetitions for each element
:return: The duplicated list
"""
_shallow_list = []
for element in i_list:
i=0
while i<n:
_shallow_... |
def belong(in_list1: list, in_list2: list) -> list:
"""
Check wheter or not all the element in list in_list1 belong
into in_list2
:param in_list1: the source list
:param in_list2: the target list where to find the element
in in_list1
:return: return True if the statem... |
class Tree:
"""
Class which represent a tree as a node,
it use more or less the same notation as we used in prolog,
the only difference is that here we omit the nil value
when there is an empty node.
"""
def __init__(self, elem, left=None, right=None):
"""
Constructo... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 08:36:12 2018
@author: Ashlee
"""
import numpy as np
# computational assignment 2 python equivalent
def system_of_ODEs(t=0, C=[6.25,0], k1=0.15, k2=0.6, k3=0.1, k4=0.2):
'''
This function defines a system of ordinary differential equations
$ \ frac{dC_A}{dt} &= -... |
def add(x,y):
""" Add two numbers together """
return x + y
def subtract(x, y):
""" returns x - y"""
return x - y |
#!/usr/bin/env python3
import csv
import json
import math
import time
API_KEY = "API KEY HERE"
TIMEOUT = 600
RADIUS_OF_EARTH = 6371000
def haversine(lon1, lat1, lon2, lat2):
""" Calculate the distance between two points on a sphere using the
haversine forumula
From:
stackoverflow.com/questions/4913... |
import time
import pandas as pd
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analy... |
def number_sum_finder():
inputString = input('put numbers [ex)3 4 6 7 9] : ')
numberList = [int(k) for k in inputString.split(' ')]
numberList = sorted(numberList)
print (numberList)
|
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
return merge(merge_sort(arr[:mid]), merge_sort(arr[mid:]))
def merge(arr1, arr2):
arr = []
i, j = 0, 0
for _ in range(len(arr1) + len(arr2)):
if j >= len(arr2) or (i < len(arr1) and arr1[i] <= arr2[j]):
... |
def binary_search(arr, value):
if len(arr) is 0:
return False
m = len(arr) // 2
if arr[m] is value:
return True
elif value < arr[m]:
return binary_search(arr[:m], value)
else:
return binary_search(arr[m + 1:], value)
|
# Used to store multiple values in one single variable.
# Create an array
cars = ["Bmw", "Volvo","Audi"]
print(cars)
# Access array
cars = ["Bmw", "Volvo","Audi"]
x = cars[1]
print(x)
# Modify
cars = ["Bmw", "Volvo","Audi"]
cars[1] = "Mercedes"
print(cars)
# Lenght
cars = ["Bmw", "Volvo","Audi"]
x = len(cars)
p... |
x = 5 #deklariranje varijabli
y = "John"
print (x) #ispis varijabli
print (y)
a, b, c = "A", "B", "C"
print (a)
print (b)
print (c)
x = "super"
print ("Python je " + x) #kombinacija s + (spajanje varijabli i teksta)
p = 5
d = 10
print (p + d)
#Globalne varijable (varijabla izvan funkcije)
x = "super"
def myfunc... |
def prime(m):
count = 0
for i in range(2,m):
if( m%i) == 0:
count +=1
if count == 0:
return True
else:
return False
n = eval(input())
num = round(n)+1
j = 5
Output = ""
while j>0:
if prime(num):
j -= 1
Output += "{},".format(num)
... |
def getNum():
s = input()
ls = list(eval(s))
return ls
def mean(numbers):
s = 0.0
for i in numbers:
s += i
return s/len(numbers)
def dev(numbers,mean):
sdev = 0.0
for num in numbers:
sdev = sdev + (num - mean)**2
return pow(sdev / (len(numbers)-1),0.5... |
#平方根格式化
#不完全版
num = input()
sqnum=pow(eval(num),0.5,3)
#result=round(sqnum,3)
if len(str(result))<=30:
print("{:+>30}".format(result))
else:
print(result)
#标准答案:
a = eval(input())
print("{:+>30.3f}".format(pow(a,0.5)))
|
#从Web解析到网络空间
'''
Python库之网络爬虫
Python库之Web信息提取
Python库之Web网站开发
Python库之网络应用开发
Python库之网络爬虫
Requests:最友好的网络爬虫功能库
提供了简单易用的类HTTP协议网络爬虫功能
支持链接池,SSL,Cookies,HTTP(S)代理等
Python最主要的页面级网络爬虫功能库
import requests
r = requests.get('https://api.github.com/user',\
auth=('user','pass'))
r.status_code
... |
alpha = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split(" ")
def binarySearch(toFind, items=[], count=1):
if len(items) == 0:
return False
midpoint = len(items) // 2
mid = items[midpoint]
# print(toFind, items, mid)
if toFind == mid:
return (True, count)
elif to... |
# -*- coding: utf-8 -*-
import string
string.ascii_lowercase
'''
The below code is a long form of the Caesar Cipher
def caesar(message, key):
coded_message = ""
alphabet = string.ascii_lowercase + " "
letters = dict(enumerate(alphabet))
key = 3
code = {letter: (place + key) % 27 for (pla... |
import random
optionsList = ["r", "p", "s"]
compChoiceFinal = None
userChoiceFinal = None
tie = "You chose the same option was the computer. Draw"
lose = "Your choice was the wrong option. You lose."
win = "Your choice was the right option! You win!"
def user_choice():
user_choice = input("Choose rock, paper, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Chap5
高阶函数
'''
fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana']
print(sorted(fruits, key=len))
################################################################
def factorial(n):
return 1 if n < 2 else n * factorial(n-1)
fact = factorial
# 构... |
#!/usr/bin/env python3
# host = localhost
# database: example1
# user: root
# password: 123456
# table: students
# 向 students 表插入数据
import pymysql.cursors
# 打开数据库连接
connection = pymysql.connect(host = 'localhost',
user = 'root',
password = '123456',
db = 'example1',
charset = 'utf8mb4')
try:... |
str1=input("Enter a string: ")
from itertools import permutations
perms = [''.join(p) for p in permutations(str1)]
newperms=set(perms)
print("Permutations: ",newperms) |
c=3
for x in range(3):
for y in range(5):
if y<(c*2)-1:
if y%2==0:
print(c,end="")
else:
print("*",end="")
print("")
c-=1
c=1
for x in range(3):
for y in range(5):
if y<(c*2)-1:
if y%2==0:
print(c,end=""... |
for x in range(8):
for y in range(8):
if x==y:
print("*", end="")
elif x+y==7:
print("*", end="")
else:
print(" ", end="")
print("") |
from tkinter import *
window = Tk("kilograms -> grams, lbs, oz")
window.geometry('1000x300')
Label(window, text="Enter Weight in Kilograms").grid(row=0)
e1_value = StringVar()
e1 = Entry(window, textvariable=e1_value)
e1.grid(row=0, column=1)
def convert_kgs_lbs():
grams = float(e1_value.get()) * 1000
p... |
# 4.3
numbers = list(range(1, 21))
for number in numbers:
print(number)
print("\n")
# 4.4
# millions = list(range(1, 1000000))
# for number in millions:
# print(number)
# print("\n")
# 4.5
millions = list(range(1, 10000001))
print(min(millions))
print(max(millions))
print(sum(millions))
print("\n")
# 4.6
odds =... |
people = []
person = {
'first_name': 'jason',
'last_name': 'ware',
'age': '42',
'city': 'cedar park',
}
people.append(person)
person = {
'first_name': 'stuart',
'last_name': 'ware',
'age': '39',
'city': 'liberty hill',
}
people.append(person)
person = {
'first_name': 'chad',
'last_nam... |
word = input("Write an english word: ")
prve_pismeno = word[0]
stred = word[1:]
convert = stred + prve_pismeno + "ay"
print(convert)
# PRIKLAD:DOMACI UKOLY2: ULOHA 9
# from random import randrange
# cislo = randrange(3)
# if cislo == 0:
# print("kamen")
# if cislo == 1:
# print("nuzky")
# else:
# ... |
import disk
import core
from datetime import datetime
def print_inventory(inventory):
for item in inventory.values():
print('{}, Price: ${}, Stock: {}, replacement: ${}'.format(
item['name'],
item['price'],
item['stock'],
item['replacement'],
))
de... |
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
jack_dit = raw_input("Dit quelque chose, Jack: ")
retour = ""
for i in jack_dit:
j = i.lower()
if (j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u' or j == 'y' or j == ' '):
retour += i
print "Sans les voyelles:", retour
raw_input() |
def init(data):
data['first'] = {}
data['middle'] = {}
data['last'] = {}
def lookup(data,label,name):
return data[label].get(name)
def store(data,full_name):
names = full_name.split()
if len(names) == 2: names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels... |
def prime(p):
for i in range(2,int(p**(1/2))+1):
if p % i ==0:
return False
return True
for i in range(2,101):
if prime(i):
print(i)
|
count = 0
while count<5:
print(count,"小于 5")
count +=1
else:
print(count,"大于或等于 5")
|
def is_leap(year):
if (year%4==0 and year%100!=0)or (year%100==0 and year%400 != 0):
return True
return False
year=int(input("请输入一个年份:"))
if is_leap(year):
print("{}是一个闰年".format(year))
else:
print("{}不是一个闰年".format(year))
|
# # python书P56的2.7
# from turtle import *
# pensize(2)
# pencolor("blue")
# for i in range(3):
# setheading(-(120*i)+30)
# forward(100)
# penup()
# goto(100*2*(3**(1/2))/3, 0)
# pendown()
# for i in range(3):
# setheading(-(120 * i) - 150)
# forward(100)
# done()
# python书P57的2.8
from t... |
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import random
import simplegui
import math
# initialize global variables used in your code
hidden=0
low =0
high=0
counter=0
# helper function to start and restart th... |
def main():
# for contador in range(1000):
# if contador % 2 != 0: #si el residuo es distinto de 0
# continue #se salta lo que viene despues del continue
# print(contador)
# for i in range(10000):
# print(i)
# if i == 5967:
# break
# text... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A collection of simple math operations
"""
def simple_add(a,b):
return a+b
def simple_sub(a,b):
return a-b
def simple_mult(a,b):
return a*b
def simple_div(a,b):
return a/b
def poly_first(x, a0, a1):
return a0 + a1*x
def poly_second(x, a0, a1... |
# Three points, P1, P2 and P3, are randomly selected within a unit square.
# Consider the three rectangles with sides parallel to the sides of the
# unit square and a diagonal that is one of the three line segments.
# Find the area of the second largest rectangle formed.
import numpy as np
import random
def pick_point... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.