text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 15:51:45 2019
@author: Paul
"""
# Solution to Advent of Code 2019 Day 17: Set and Forget
import random
import numpy as np
import matplotlib.pyplot as plt
import time
def read_data(filename):
"""
Reads csv file into a list, and converts stri... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 10:53:42 2019
@author: Paul
"""
# Advent of Code Day 16: Flawed Frequency Transmission
def read_data(filename):
"""
Reads data file into a list of ints.
"""
int_data = []
f = open(filename, 'r')
for line in f:
... |
str=raw_input('enter the string:')
str1=str+'.'
print(str1)
|
a=input()
if a.count('(')==a.count(')'):
print("yes")
else:
print("no")
|
import numpy as np
arredondar = lambda num: float('%.6f' % num) # função que arredonda o nº para 6 casas decimais
def isPossibleandDeterm(matrix): # função que determina se o sistema é possível ou não
det = np.linalg.det(matrix) # Cálculo do determinante
if (det > 0) or (det < 0): # Sistema p... |
def swap(d, key1, key2):
if key1 == key2:
return
val1 = d[key1]
val1 = val1.copy() if isinstance(val1, dict) else val1
val2 = d[key2]
val2 = val2.copy() if isinstance(val2, dict) else val2
d[key1], d[key2] = val2, val1
|
import unittest
from benedict.core import items_sorted_by_keys as _items_sorted_by_keys
from benedict.core import items_sorted_by_values as _items_sorted_by_values
class items_sorted_test_case(unittest.TestCase):
"""
This class describes an items sorted test case.
"""
def test_items_sorted_by_keys(s... |
#CLASSES
class Pet:
def __init__(self,name,age,color):
self.name = name
self.age = age
self.color = color
class Dog(Pet):
def __init__(self,name,age,color,breed,attitude):
self.breed = breed
self.attitude = attitude
Pet.__init__(self,name,age,color)
... |
from gesture import *
from player import *
import time
import random
import getpass
class Game:
def __init__(self):
self.rounds = 0
self.current_round = 0
self.players = 0
self.player_1 = None
self.player_2 = None
self.run = False
self.rock = Rock()
... |
import math
def detect_triangle(b , c, d):
# -1 : nhap sai
# -2 : khong lam tam giac
# 0 : tam giac deu
# 1 : tam giac vuong can
# 2 : tam giac can
# 3 : tam giac vuong
# 4 : tam giac thuong .
a = [0]*3
a[0] = b;
a[1] = c;
a[2] = d;
try :
a[1] = float(a[1])
a[2] = float(a[2]... |
# Budget App
# Create a Budget class that can instantiate objects based on different budget categories like food, clothing, and entertainment. These objects should allow for
# 1. Depositing funds to each of the categories
# 2. Withdrawing funds from each category
# 3. Computing category balances
# 4. Transferring b... |
# Python program to translate
# speech to text and text to speech
import webbrowser
import speech_recognition as sr
import pyttsx3
import wikipedia
from googlesearch.googlesearch import search
from datetime import datetime
# Initialize the recognizer
r = sr.Recognizer(... |
import re
import string
from collections import defaultdict
from typing import Dict, Tuple, List
skip_words = {"и", "а", "в", "я", "на", "не", "что",
"с", "она", "они", "оно", "он", "как",
"мне", "меня", "но", "его", "ее", "это",
"к", "так", "за", "по", "же", "из", "то",
... |
# --- Exercício 3 - Funções
# --- Escreva uma função para listar pessoas cadastradas:
# --- a função deve retornar todas as pessoas cadastradas na função do ex1
# --- Escreva uma função para exibi uma pessoa específica:
# a função deve retornar uma pessoa cadastrada na função do ex1 filtrando por id
def pessoas_... |
#--- Exercício 5 - Funções
#--- Crie uma função para calculo de raiz
#--- A função deve ter uma variável que deternine qual é o indice da raiz(raiz quadrada, raiz cubica...)
#--- Leia um número do console, armazene em uma variável e passe para a função
#--- Realize o calculo da raiz e armazene em uma segunda variável e... |
# A List is a collection which is ordered and changeable. Allows duplicate members.
# Create list
# numbers = [1, 2, 3, 4, 5]
# Using a constructor
numbers = list((1, 2, 3, 4, 5))
print(numbers)
|
import string
from random import randint
str1 = string.printable
print(str1)
print(len(str1))
for i in range (6):
print (str1[randint(1,100)],end=" ")
|
import numpy as np
def sigmoid():
"""
Returns a lambda function that takes the form of the sigmoid function.
The package bigfloat is used to get more precision
:return: float
"""
return lambda z: float(1 / (1 + np.exp(z)))
def perceptron():
"""
Returns a lambda function that takes th... |
'''
conditional statements
----------------------
if (con):
# something
elif (con):
# something
else:
# something
'''
def main():
num = 25
if (num<20):
print("%s is smaller than 20" % (num))
elif(num < 30):
print("%s is smaller than 30" % (num))
else:
print("%s is ... |
# Built-in Data Types
# Variables can store data of different types, and different types can do different things.
# str
x = "Hello World"
print(x)
print(type(x))
# int
x = 20
print(x)
print(type(x))
# float
x = 20.7
print(x)
print(type(x))
# complex
x = 1-8j
print(x)
print(type(x))
# list
x = ["apple", "banana", "cherr... |
# Built-in Math Functions
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
x = abs(-7.25)
print(x)
x = pow(4, 3)
print(x)
# Math Module
# Python has also a built-in module called math, which extends the list of mathematical functions.
import math
x = math.sqrt(64)
print(x)
x = math.ceil(1.4)
y = math.floor(1.4)
... |
# Python Dates
# A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
|
# Global Variables
# Variables that are created outside of a function are known as global variables.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
x = "awesome"
def myfunc1():
x = "fantastic"
print("Python is " + x)
myfunc1()
print("Python is " + x)
# global Keyword
'''
Normally, when you create a... |
import requests
import sqlite3
from bs4 import BeautifulSoup
# author: Hope Foreman
# date: 11, Oct 2021
# setting up the database
database_name = 'golfers.db'
conn = sqlite3.connect(database_name)
c = conn.cursor()
# setting up connection with beautiful soup and web page
url = 'http://www.owgr.com/rank... |
import math
def main():
letters, words, sentences = 0, 1, 0
sentence_test = ["!", ".", "?"]
text = input("Text: ")
for i in text:
letters += 1 if i.isalpha() else 0
words += 1 if i.isspace() else 0
sentences += 1 if i in sentence_test else 0
print(letters, words, sentence... |
target = "zymotic"
with open('/home/zhang/learn_python/github_repo/python/word-play/words.txt') as f:
words = f.read()
words = words.split()
target = ["one", "two", "three", "four", "five", "six", "seven"]
with open('testwords.txt') as f:
words = f.read()
words = words.split()
def search(target)... |
print('hello world')
message = 'Hello World'
print(message)
print(len(message))
print('*' * 10)
message = '"Hello" World'
print(message)
book = "zhang's book"
print(book)
print('*' * 10)
# Wrong
# book = 'zhang's book'
# print(book)
message = """zhang
li
wang"""
print(message)
print(len(message))
print('*... |
word = 'abcasfsddfds'
def is_abecdarian(word):
first = 0
for letter in word[:-1]:
if letter > word[first + 1]:
return False
first += 1
return True
print(is_abecdarian(word))
def is_abecdarian_2(word):
i = 0
while i <= len(word) - 2:
current = word[... |
# index [0, 1, 2, 3...]
courses = ['History', 'Math', 'Math', 'Phythsics', 'CompSci']
print(courses)
print(len(courses))
print(courses.count('Math'))
print(courses[3])
print(courses[-1])
print(courses[:-1])
print(courses[:])
print(courses[0:2])
print('*' * 10)
# add item
courses = ['History', 'Math', 'Math... |
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = f'{self.first}.{self.last}@email.com'
self.pay = pay
def fullname(self):
return f'{self.first} {self.last}'
def apply_raise(self):
... |
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def insercion(I):
for i in range(len(I)):
for j in range(i,0,-1):
if(I[j-1]>I[j]):
aux=I[j]
I[j]=I[j-1]
I[j-1]=aux
print(I)
>>> ... |
import pygame
import games.zeilen.Globals as globals
import games.zeilen.Resources as resources
tiles = list()
#Background class
#The background class is basicly the water tile. Several instances of this are created and used to fill the screen with water.
class Background(pygame.sprite.Sprite):
scroll_speed = 1 ... |
#!/bin/python3
import random
print('''
Random Code Generator
=====================
''')
# Characters to use
chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789'
length = input('Code length?')
length = int(length)
nb = input('How many Codes?')
nb = int(nb)
csvData = []
for pwd in range(nb):
password = ''
for c in rang... |
from tkinter import messagebox, Tk, simpledialog
if __name__ == '__main__':
window = Tk()
window.withdraw()
name = simpledialog.askstring(None, 'Please enter a name')
if name.lower() == 'charlie':
messagebox.showinfo('Charlie', 'Charlie is very enthusiastic')
elif name.lower() == 'zachary':... |
from functools import reduce as _reduce
def gen_cand_and_clean(votes):
"""
params:
- votes (list (dict {'a : Ord 'b})): The list of votes, which are
candidates mapped to a preference
returns:
- candidates (set 'a): The set of candidates
- cleaned votes (list (dict {'a : Ord 'b}))
This utility function ... |
from random import randrange
# 3번 연속이기면 승리
def game():
com = randrange(0, 3)
print(' COM: ', com)
user = int(input('가위 0, 바위 1, 보 2 \n YOU: '))
if com < user :
com = com + 3
result = com -user
result_str = ''
if result == 2:
result_str = 'USER WIN'
if result == 1:
... |
from random import randint
class Board(object):
def __init__(self, size):
assert isinstance(size, int)
self.size = size
self.positions = [["-"] * self.size for i in range(self.size)]
def __repr__(self):
board_string = '\n'.join(['|'.join(self.positions[i]) for i in r... |
"""
Chapter 6, Our first NN with
backpropagation and conditional correlation
"""
import numpy as np
np.random.seed(1)
def relu(x):
# Our Relu method for conditional correlation in the middle layer
# it will set all negative numbers to 0, "turning off" middle nodes.
return (x > 0) * x
def relu... |
# define the fibonacci() function below...
def fibonacci(n):
# base cases
if n == 1:
return n
if n == 0:
return n
# recursive step
print("Recursive call with {0} as input".format(n))
return fibonacci(n - 1) + fibonacci(n - 2)
fibonacci(5)
# set the appropriate runtime:
# 1, logN, N, N^2, 2^N,... |
# Elliptic Curve Implementation
import collections
Coord = collections.namedtuple("Coord", ["x", "y"])
def inv(n, q):
"""
Find the inverse on n modulus q
"""
return egcd(n, q)[0] % q
def egcd(a, b):
"""
This function performs an extended GCD according to euclid's algorithm.... |
def crypt(args, x):
ciphertext = str(args)
shift = int(x)
ciphertext = ciphertext.split()
sentence = []
for word in ciphertext:
cipher_ords = [ord(x) for x in word]
plaintext_ords = [o + shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
... |
import pygame,random
from pygame.locals import*
screen_width = 800
screen_height = 800
pygame.init()
game_display = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Tic Tac Toe')
clock = pygame.time.Clock()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
blue = (0,0,255... |
import numpy as np
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
N_of_english_chars = 26
# frequency taken from http://en.wikipedia.org/wiki/Letter_frequency
englishLetterFreq = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76... |
def outer(a):
def inner(*args, **kwargs):
for arg in args:
if not isinstance(arg, str):
print("Not all arguments are string")
return inner
for kwarg in kwargs.values():
if not isinstance(kwarg, str):
print("Not all argumen... |
# 실수(real number) 1개를 입력받아 줄을 바꿔 3번 출력해보자.
# 예시
# ...
# print(f) #f에 저장되어있는 값을 출력하고 줄을 바꾼다.
# print(f)
# print(f)
# 와 같은 방법으로 3번 줄을 바꿔 출력할 수 있다.
# 참고
# python 코드 사이에 설명(주석)을 작성해 넣고 싶은 경우 샵('#') 기호를 사용하면 된다.
# #가 시작된 위치부터 그 줄을 마지막까지는 python 인터프리터에 의해서 실행되지 않는다.
# 소스코드 부분 부분에 설명, 내용, 표시를 한 줄 설명으로 넣을 경우에 편리하게 사용할 수 있다.... |
# 빨강(red), 초록(green), 파랑(blue) 빛을 섞어 여러 가지 다른 색 빛을 만들어 내려고 한다.
# 빨강(r), 초록(g), 파랑(b) 각 빛의 가짓수가 주어질 때,
# 주어진 rgb 빛들을 섞어 만들 수 있는 모든 경우의 조합(r g b)과 만들 수 있는 색의 가짓 수를 계산해보자.
# **모니터, 스마트폰과 같은 디스플레이에서 각 픽셀의 색을 만들어내기 위해서 r, g, b 색을 조합할 수 있다.
# **픽셀(pixel)은 그림(picture)을 구성하는 셀(cell)에서 이름이 만들어졌다.
r, g, b = input().split(' ... |
# 친구들과 함께 3 6 9 게임을 하던 영일이는 잦은 실수 때문에 계속해서 벌칙을 받게 되었다.
# 3 6 9 게임의 왕이 되기 위한 369 마스터 프로그램을 작성해 보자.
# ** 3 6 9 게임은?
# 여러 사람이 순서를 정한 후, 순서대로 수를 부르는 게임이다.
# 만약 3, 6, 9 가 들어간 수를 자신이 불러야 하는 상황이라면, 수를 부르는 대신 "박수(X)" 를 쳐야 한다.
# 33과 같이 3,6,9가 두 번 들어간 수 일때, "짝짝"과 같이 박수를 두 번 치는 형태도 있다.
# 참고
# ...
# for i in range(1, n+1) :
# ... |
# 공백을 두고 입력된정수(integer) 2개를 입력받아 줄을 바꿔 출력해보자.
# 예시
# a, b = input().split()
# print(a)
# print(b)
# 과 같은 방법으로 두 정수를 입력받아 출력할 수 있다.
# 참고
# python의 input()은 한 줄 단위로 입력을 받는다.
# input().split() 를 사용하면, 공백을 기준으로 입력된 값들을 나누어(split) 자른다.
# a, b = 1, 2
# 를 실행하면, a에는 1 b에는 2가 저장된다.
# (주의 : 하지만, 다른 일반적인 프로그래밍언어에서는 이러한 방법을 지원하지... |
# 10진수를 입력받아 16진수(hexadecimal)로 출력해보자.
# 예시
# a = input()
# n = int(a) #입력된 a를 10진수 값으로 변환해 변수 n에 저장
# print('%x'% n) #n에 저장되어있는 값을 16진수(hexadecimal) 소문자 형태 문자열로 출력
# 참고
# 10진수 형태로 입력받고
# %x로 출력하면 16진수(hexadecimal) 소문자로 출력된다.
# (%o로 출력하면 8진수(octal) 문자열로 출력된다.)
# 10진법은 한 자리에 10개(0 1 2 3 4 5 6 7 8 9)의 문자를 ... |
# 정수 2개(a, b)를 입력받아
# a를 b번 곱한 거듭제곱을 출력하는 프로그램을 작성해보자.
# 예시
# ...
# c = int(a)**int(b)
# print(c)
# 참고
# python 언어에서는 거듭제곱을 계산하는 연산자(**)를 제공한다.
# 일반적으로 수학 식에서 거듭제곱을 표현하는 사용하는 서컴플렉스/케릿 기호(^)는 프로그래밍언어에서 다른 의미로 쓰인다.
a, b = input().split(' ')
result = int(a) ** int(b)
print(result) |
# 점수(정수, 0 ~ 100)를 입력받아 평가를 출력해보자.
# 평가 기준
# 점수 범위 : 평가
# 90 ~ 100 : A
# 70 ~ 89 : B
# 40 ~ 69 : C
# 0 ~ 39 : D
# 로 평가되어야 한다.
# 예시
# ...
# if n>=90 :
# print('A')
# else :
# if n>=70 :
# print('B')
# else :
# if n>=40 :
# print('C')
# else :
# print('D')
# ...
# 참고
# 여러 조건들... |
word = "tallie"
#removes letter from alphabet once guessed
def remove_guessed_letter(word): #remove letter once guessed
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for charactors in list(alphabet):
if charactors in word:
alphabet = alphabet.replace(charactors," ")
return alphabet
guess1 = "t"
print remove_guess... |
age = input("Enter_your_age_here:")
if 18 <= int(age):
print("You are an adult!")
else:
print("You are a small boy")
input("Press enter to exit") |
import random
possible_cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
print("Please note that the dealer stands at 16.")
while True:
players_hand = ""
dealers_hand = ""
while players_hand == "" and dealers_hand == "":
players_hand = random.choice(possible_cards) + random.choice(possi... |
# Dropbox Python Authentication Tutorial
# Include Dropbox SDK libraries
from dropbox import client, rest, session
# Set APP_KEY, APP_SECRET, and ACCESS_TYPE
APP_KEY = 'ongci9riiqkrtll'
APP_SECRET = 'jyae8eqk2088hdp'
ACCESS_TYPE = 'app_folder' # application has access to application folder only
# Set up session vari... |
from selenium import webdriver
driver = webdriver.Chrome()#install the chrome divers for this code to work(accordance to your chrome version)
driver.get('https://web.whatsapp.com/')
name = input('Enter the name of user or group : ')#whom you wanna sent
msg = input('Enter your message : ')#what you wanna sent
input('Ent... |
#
# Copyright (c) 2018 Andera del Monaco
#
# The following example shows how to import the Yahoo Finance Python Interface
# into your own script, and how to use it.
#
# In particular, we will download the timeseries of APPLE close daily price from 2017-09-1 to 2018-08-31,
# and then will plot them using the matplotli... |
class Rect(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self._x_center = x + (width / 2)
self._y_center = y + (height / 2)
@property
def x_center(self):
return int(self.x +(self.wid... |
# print('enter a number')
""" a = int(input())
print('Enter a second number')
b = int(input())
c = a+b
print("out put is \n",c) """
'''
x = input()[0]
print(x);
'''
'''x = eval(input())
print(x)
'''
"""
if 1 != 1 :
print('dfd')
print(5464)
print(445)
else:
print(54365436)
print... |
f = open('My Personal Details', 'r')
print(f)
# print(f.read()) # print entire content
# print(f.readline()) # print 1st line
# print(f.readline()) # print 2nd line it has inbuild next function
# print(f.readline(3)) # print mentioned line number
# print(f.readable()) # it returns boolean which file is ... |
n=input("enter string\n")
k=input("enter key\n")
k=int(k)
a=""
b=" "
for i in range(len(n)):
b=ord(n[i])-97
b=(b+k)%26
b=chr(b+97)
a=a+b
print("Encrypted")
print(a)
c=""
b=" "
for i in range(len(a)):
b=ord(a[i])-97
b=(b-k)%26
b=chr(b+97)
c=c+b
print("Decrypted")
print(c)
|
####################序列通用操作####################
#Indexing
greeting = "Hello"
print(greeting[0]) #第一个元素
print(greeting[-1]) #右起第一个元素
print("Hello"[1]) #序列字面量直接使用索引,不需要借助变量引用
#print(input("Year: ")[3]) #直接对函数返回值进行索引操作
#Slicing
tag = "<a href='http://www.python.org'>Python web site</a>"
print(tag[9:30])
print(tag[32:-4])
... |
####################更加抽象####################
#创建自己的类
__metaclass__ = type #确定使用新式类
#新式类的语法中,需要在模块或脚本开始的地方使用上述语句
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print("Hello, world! I'm %s" % self.name)
#self是对于对象自身的引用,没有它... |
####################网络编程####################
#John Goerzen的Foundations of Python Network Programming
#socket模块
#网络编程中的一个基本组件就是套接字(socket),基本上是两个端点的程序之间的“信息通道”
#Python中的大多数网络编程都隐藏了socket模块的基本细节,不直接和套接字交互
#套接字包括两个:服务器套接字和客户机套接字
#一个套接字就是socket模块中的socket类的一个实例,实例化需要3个参数
#第1个参数是地址族(默认socket.AF_INET)
#第2个参数是流(socket.SOCK_ST... |
# grocery list
grocery=['Chocolate','Milk','Cereal']
for i in grocery:
print(i)
|
from tkinter import *
root = Tk()
v = IntVar()
def show():
win = Tk()
Label(win,bg = "white",text = str(v.get())).pack()
#for i in range(5):
bt = Checkbutton(root,text = "455",
variable = v,
)
Button(root,text="text",command = show).pack()
bt.pack()
... |
from tkinter import *
root = Tk()
enter = Entry(root)
ls = Listbox(root,selectmode = "extended")
v = StringVar()
#l = StringVar()
enter["textvariable"] = v
enter.pack()
def show():
val = ls.get(ls.curselection()) #返回列表框选定的值
v.set(val) #设置在entry显示的值
t = ["chen","li","shen","liu","tang"]
... |
#!/usr/bin/env python
# coding: utf-8
# ## Assignment
# ### Number of Task :: 3
# #### 1. A list of all cricket players who have ever played ODI matches
# #### 2. Runs they have made every year in their career
# #### 3. Cummulify the scores by year for each player
#
#
#
# ##### **Note :: All the data are fetch... |
"""
Декоратор — это структурный паттерн проектирования, который позволяет динамически добавлять объектам новую
функциональность, оборачивая их в полезные «обёртки».
Применимость:
Когда вам нужно добавлять обязанности объектам на лету, незаметно для кода, который их использует.
Недостатки:
1) Трудно конфигурировать мног... |
from typing import List
def lengthOfLIS(nums: List[int]) -> int:
if not nums:
return 0
dp = []
for i in range(len(nums)):
dp.append(1)
for j in range(i):
if nums[i] > nums[j]:
# 这一步是关键,dp[i]在里层循环的时候可能会被多次更新,i越到后面越大,
# dp[i]被改写的概率同样越大,这里比较的... |
'''
有一段不知道具体长度的日志文件,里面记录了每次登录的时间戳,已知日志是按顺序从头到尾记录的,
没有记录日志的地方为空,要求当前日志的长度。
'''
import math
import numpy as np
def binextend_log(lines, high):
# print('binextend_log [high]: ', high)
lines_size = len(lines)
high_ext = high*2
index = min(high_ext, lines_size)
print('binextend_log [high]: %s, [high_ext... |
# Implementing Mergesort
def mergeSort(arr):
if len(arr)==1:
return arr
else:
mid = int(round((len(arr)/2)))
return merge(
mergeSort(arr[:mid]),
mergeSort(arr[mid:len(arr)])
)
def merge(l1,l2):
if len(l1)==0:
return l2
if len(l2)==0:
... |
class doubleLinkedList():
def __init__(self,key = None,prev=None,next=None):
self.next = next
self.prev = prev
self.key = key
def add(self,key):
element = doubleLinkedList(key,self,self.next)
if self.next:
self.next.prev = element
self.next = element... |
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2] = "2 - 菜鸟工具"
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}
print (dict['one']) # 输出键为 'one' 的值
print (dict[2]) # 输出键为 2 的值
print (tinydict) # 输出完整的字典
print (tinydict.keys()) # 输出所有键
print (tinydict.values()) # 输出所有值
import ... |
print("TABELA DE PREÇOS");
print("Produt o Até 5 Kg Acima de 5 Kg");
print("Morango R$ 2,50 por Kg R$ 2,20 por Kg");
print("Maçã R$ 1,80 por Kg R$ 1,50 por Kg");
qtd1 = int(input("\nQual a quantidade em Kg de Morango: "));
qtd2 = int(input("Qual a quantidade em Kg de Maçã: "... |
num = int(input("Digite um numero: "));
if(num > 0):
print(num, " é positivo");
else:
print(num, " é negativo");
|
print("TABELA DE PREÇOS");
print("Produtos/Tipo Até 5 Kg Acima de 5 Kg");
print("File Duplo - 1 R$ 4,90 por Kg R$ 5,80 por Kg");
print("Alcatra - 2 R$ 5,90 por Kg R$ 6,80 por Kg");
print("Picanha - 3 R$ 6,90 por Kg R$ 7,80 por Kg");
prod = int(input("\nQual a o produt... |
popA = 80000;
popB = 200000;
print("População A inicial: ", popA);
print("População B inicial: ", popB);
a = 0;
b = 2;
anos = 0;
while a < b:
if(popA >= popB):
a = 2;
print("\nPara que a Poupulação A ultrapasse a População B levará",anos,"anos\n");
print("População ... |
x = 1;
while x < 2:
nomeUser = input("Insira o seu nome de Usuário: ");
senhaUser = input("Insira uma sua senha: ");
if(senhaUser.lower() != nomeUser.lower()):
x = 2;
print("Sucesso ao fazer login!");
else:
print("\nErro. Digite novamente! Senha não p... |
#count even and odd no in a list
a=[1,5,3,9,10,11,20]
print(a)
count=0
c=0
for i in a:
if i%2==0:
count=count+1
else:
c=c+1
print("even no in list =",count)
print("odd no in list =",c)
|
# -*- coding: utf-8 -*-
# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
def case1():
'''使用数字,每种语言都可以用'''
l = []
for a in range(1,5):
for b in range(1,5):
for c in range(1,5):
# print('a =', a, 'b =', b, 'c =', c)
if (a != b) & (b != c) & (a != c):
... |
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-06 20:43:00
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-06 21:41:14
# 打印出如下图案(菱形):
# *
# ***
# *****
# *******
# *****
# ***
# *
def print_Rhombus(n):
# 打印菱形,输入奇数行
if n % 2 == 0:
print("输入错误,退出程序")
re... |
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-03 21:45:57
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-03 21:53:31
# 输入一行字符,分别统计出其中的英文字符、空格、数字和其他字符的个数
def get_nums(s):
a, b, c, d = 0, 0, 0, 0
for i in s:
if i.isdigit():
a += 1
elif i.isalpha():
... |
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-20 18:27:42
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-20 18:34:50
# 有两个磁盘文件A.txt和B.txt,各存放了一行字母,要求把这两个文件中的信息合并按字母顺序排列,输出到新文件C.txt中
def run():
with open("A.txt", "r") as f:
text1 = f.read()
with open("B.txt", "r") as f... |
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-20 17:08:46
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-20 17:15:57
# 输入一个奇数,然后判断最少几个9除以该数的结果为整数
def function(x):
i = 1
while True:
y = int("9"*i)
if y % x == 0:
print("%d 可以被 %d 整除" % (x, y))
... |
# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date: 2020-01-20 16:55:01
# @Last Modified by: MirroAi
# @Last Modified time: 2020-01-20 17:03:15
# 求0到7能组成的奇数个数,每个数字只能使用一次
def run():
count = 0
for i in range(1, 9): # 最多可组成8位数
if i == 1:
count += 4
elif i == 2:
cou... |
from turtle import Turtle, Screen
import random
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_choice = screen.textinput(title="Choose a car", prompt="Red, Green OR Yellow?")
cars = ["Red", "Green", "Yellow"]
vertical_positions = [-70, 0, 70]
created_cars = []
# Create cars
for car in car... |
def isUgly(n):
if n == 0:
return False
elif n == 1:
return True
else:
if (n % 5 == 0):
n //= 5
elif (n % 3 == 0):
n //= 3
elif (n % 2 == 0):
n //= 2
else:
return False
return isUgly(n)
print(isUgly(15))
... |
class Caesar():
#CS50X Caesar task in python
def caesar_main(self):
key = int(input("Key (number) : ")) # get key number
caesar = input("Text : ") # get string
new_caesar = "" #converted string
for i in caesar: #loop in given string
if i.isalpha(): # if i is alpha (a-z)... |
#!/bin/local/python
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
max_num = reduce(lambda x,y : x*y, range(1,21))
test= 0
found=1
while found != 0 and ... |
#!/usr/bin/python
"""Find the sum of all the multiples of 3 or 5 below 1000."""
sum=0
for y in xrange(3,1000):
if y % 3 == 0 or y % 5 == 0:
sum+=y
print sum
|
#!/usr/bin/python
"""
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the divisors of the first seven triangle numbers:
1: 1
3: 1,3
6:... |
import random
import string
def generate_codes(number_of_codes: int, code_length: int):
"""Generates X number of random codes based on the provided length.
Pramas:
-------
number_of_codes (int): The number of the random codes that shall be
created which should be unique also.
... |
import pygame
import sys
import random
# 这节课主要内容是添加了分数和生命值 改变小球的方向
pygame.init()
screen = pygame.display.set_mode((640,700))
pygame.display.set_caption("BAll")
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
ball_x = 110
ball_y = 100
rect_x = 300
rect_y = 650
speed = 10
speedx ... |
import pygame
import sys
# 1.初始化pygame
pygame.init()
# 2. 设置窗口大小
screen = pygame.display.set_mode((640, 480)) # 设置窗口大小 显示窗口
width = 640
height = 480
# 3. 设置窗口名字
pygame.display.set_caption('BALL')
ball = pygame.image.load('./img/ball.png') # 加载图片
ballrect = ball.get_rect() # 获取矩形区域
# ballrect = py... |
'''
Python算术运算符
+ 加 - 两个对象相加 a + b 输出结果 31
- 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -11
* 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 210
/ 除 - x 除以 y b / a 输出结果 2.1
% 取模 - 返回除法的余数 b % a 输出结果 1
** 幂 - 返回x的y次幂 a**b 为10的21次方
// 取整除 - 向下取接近除数的整数
Python比较运算符
== 等于 - 比较对象是否相等 (a == b) 返回 False。
!= 不等于 - 比较两个对象是否不相等 (a... |
# 读取数据和简单的数据探索
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris() # 可以看成字典
print(iris.keys())
print(iris.data) # 拿到数据
print(iris.data.shape)
x = iris.data[:,:2] # 只能绘制2维图像,所以只要前两列
plt.scatter(x[:,0],x[:,1])
plt.show()
|
'''
常用算法:
穷举法 - 又称为暴力破解法,对所有的可能性进行验证,直到找到正确答案。
贪婪法 - 在对问题求解时,总是做出在当前看来
最好的选择,不追求最优解,快速找到满意解。
分治法 - 把一个复杂的问题分成两个或更多的相同或相似的子问题,再把子问题分成更小的子问题,
直到可以直接求解的程度,最后将子问题的解进行合并得到原问题的解。
回溯法 - 回溯法又称为试探法,按选优条件向前搜索,当搜索到某一步发现原先选择并不优或达不到目标时,
就退回一步重新选择。
动态规划 - 基本思想也是将待求解问题分解成若干个子问题,先求解并保存这些子问题的解,避免产生大量的重复运算。
穷举法例子:百钱百鸡和五人分鱼。
# 公鸡5元一只 ... |
import numpy as np
# numpy 中的矩阵的操作
# print(np.__version__)
# array = np.array([[1,2,3],[2,3,4]]) # 只能有一种类型
# print(array.dtype)
# array[1][1] = 5.0
# print(array)
#
# l = [i for i in range(10)]
#
# print(l)
#
# print(np.zeros(10,dtype=float))
#
# print(np.zeros(shape=(3,5)))
#
# print(np.ones(shape=(3,5)))
#
# print... |
# -*- coding: utf-8 -*-
# @Time : 2019/7/21 9:59
# @Author : liuqi
# @FileName: day10.py
# @Software: PyCharm
# 猜字游戏
import random
x = random.randint(0, 99)
while(True):
num = input("请猜猜是多少")
if(num.isdigit()):
num = int(num)
if(x == num):
print("恭喜你,猜对了")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.