text stringlengths 37 1.41M |
|---|
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Maiores e Menores
lista_menores = []
lista_maiores = []
pivot = int(raw_input())
while True:
numero = int(raw_input())
if numero < 0:
break
if numero <= pivot:
lista_menores.append(numero)
else:
lista_maiores.append(numero)
print... |
# coding: utf-8
# Cálculo da média em Álgebra Vetorial
nota1 =float(raw_input())
nota2 =float(raw_input())
media =float((nota1 + nota2) / 2)
print 'Nota 1: ',nota1
print 'Nota 2: ',nota2
print 'Média : ',media
|
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Calculadora
def soma(a,b):
soma = a + b
return soma
def subtracao(a,b):
sub = a - b
return sub
def multiplicacao(a,b):
multi = a * b
return multi
def divisao(a,b):
divi = a / b
return divi
while True:
entrada = raw_input().spli... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Soma os Divisores do Primeiro Elemento de uma Lista
lista = []
for i in range(11):
numero = int(raw_input())
lista.append(numero)
numero_comparador = lista[0]
lista = lista[1:]
for i in lista:
if numero_comparador % i == 0:
print i
|
# coding: utf-8
# Eduardo Pereira / Programação 1
import math
print'Cálculo da Superfície de um Cilindro'
print'---'
medida_diametro = float(raw_input('Medida do diâmetro? '))
medida_altura = float(raw_input('Medida da altura? '))
raio = float (medida_diametro / 2)
area = float ((2 * math.pi * raio) * (raio + medida_al... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Agenda Ordenada
def agenda_ordena(dados,nome):
lista_agenda = []
for d in range(len(dados)):
troca = False
for i in range(0,len(dados) -1):
if dados[i] > dados[i+1]:
dados[i],dados[i+1] = dados[i+1], dados[i]
troca = True
... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Hospital de Trauma
def cadastra(fila, nome, prioridade):
j = 0
for d in range(len(prioridade)):
troca = False
for i in range(0,len(fila)):
if fila[i] == prioridade[d]:
nome[i],nome[j] = nome[j], nome[i]
j += 1
troca = Tru... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Quantos Comeram
def quantos_comeram(N,fila):
i = 0
vendas = 0
while True:
if fila[i] < N:
vendas += fila[i]
N -= fila[i]
elif fila[i] == N:
vendas += N
N -= fila[i]
break
elif fila[i] > N:
break
i += 1
return ven... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Analisa Chave
vogais = 'aeiou'
senha = raw_input()
cont = 0
segura = True
d = 0
while d < (len(senha)-2):
if senha[d] == senha[d+1] and senha[d] == senha[d+2]:
print'Chave insegura. 3 caracteres consecutivos iguais.'
segura = False
... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Maioridade Penal Função
def maioridade_penal(string1,string2):
string1 = string1.split()
string2 = string2.split()
string_nova = ''
for d in range(len(string2)):
if int(string2[d]) >= 18:
if d+1 < len(string2):
string_nova += str... |
# coding: utf-8
# Aluno: Eduardo Pereira
# Matricula: 117210342
# Atividade: Filtrando Elementos e Alterando uma Lista
def filtra_altera_lista(num, lista):
for i in range((len(lista) -1),-1,-1):
if i % num != 0:
lista.pop(i)
|
# coding: utf -8
# Divisores próprios
# Eduardo Pereira dos Santos / Programação 1 / Matricula: 117210342
entrada = int(raw_input())
for i in range (1 ,entrada):
if entrada % i == 0:
print i
|
# 3a. (15 points) Add a year data member to the Date class:
# i. Allow the class constructor to get an additional argument denoting the year
# ii. If the year is not provided in the constructor, the class should assume it is 2018 (Hint: remember the
# default value option in function definition)
# iii. When printing in... |
### Chris Braden PS2 question 3
##
## GIVEN: an input file to copy and a name for the copied file
## RETURN: the input file copied to a new file named with the filename
import sys
original_file = open(sys.argv[1], "r") #open the file named in the first arg
original_content = original_file.read() #read the file conten... |
### Chris Braden PS1 question 5
##
## GIVEN: three command line arguments
## Return: the three arguments as uppercase letters on a single line without spaces between
import sys # load sys package
arg1 = sys.argv[1] # read arguments
arg2 = sys.argv[2]
arg3 = sys.argv[3]
arg1 = arg1.upper() # convert arguments to upper... |
### Chris Braden PS5 question 3
##
## GIVEN: a file containing organisms and sequences (as above), and a query species
## RETURN: the corresponding sequence for the query species, or a message if the query species isn't in the file
################# PACKAGES
import sys
################# FUNCTIONS
def file_to_dict(f... |
#import sys
#sum = 0
#for i in sys.argv[1:]:
# i=int(i)
# sum = sum + i
# print sum
#import sys
#myfile = open(sys.argv[1],'r')
#mylist = list(myfile.readlines())
#i = 0
#for line in mylist:
# words = line.split()
# print len(words)
import sys
myfile = open(sys.argv[1],'r')
for x in myfile:
wor... |
c = 0.09290304
D = {'feet':'meter', 'meter':'feet'}
unit = input('Choose the unit you will enter: feet/meter')
while unit.lower() not in ['feet', 'meter']:
unit = input('Invalid. Choose the unit you will enter: feet/meter')
while 1:
length = input(f'What is the length of the room in {unit.lower()}')
... |
while 1:
a = input('''Press C convert from Fahrenheit to Celsius.
Press F to convert from Celsius to Fahrenheit.
Press CK to convert from Celsius to Kelvin
Press FK to convert from Fahrenheit to Kelvin
Press KC to convert from Kelvin to Celsius
Press KF to convert from Kelvin to Fahrenheit''')
if a.upper... |
# What is the principal amount? 1500
# What is the rate? 4.3
# What is the number of years? 6
# What is the number of times the interest
# is compounded per year? 4
# $1500 invested at 4.3% for 6 years
# compounded 4 times per year is $1938.84.
principal=input("What is the principal amount? ")
rate=input("Wha... |
A = {'WI', 'NY', 'LA','WISCONSIN', 'NEW YORK', 'LOS ANGELES'}
while 1:
amount = input('What is the order amount?')
try:
amount = float(amount)
break
except: print('Invalid')
state = input('What is the state?')
r = 5.5
subtotal = amount
tax = 0.01 * r * amount
total = amount * (1 +... |
people=input('How many people? ')
pizzas=input('How many pizzas do you have? ')
num_pizzas=8*int(pizzas)
get=num_pizzas/int(people)
leftover=num_pizzas%int(people)
print('''%d people with %d pizzas
Each person gets %d pieces of pizza.
There are %d leftover pieces.'''%(int(people),int(pizzas),ge... |
S = 0
while 1:
n = input('Enter the number of inputs? ')
try:
n = int(n)
break
except:
print('Invalid')
for i in range(n):
a = input('Enter a number:')
try:
a = int(a)
S += a
except:
print('Invalid')
print(f'The total is {S}.') |
print("Enter two strings and I'll tell you if they are anagrams: ")
def isAnagram(a,b):
if len(a) == len(b):
A = ''
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
A = A + a[i]
b = b[:j] + b[j+1:]
... |
D = {'item 1':25, 'item 2':10, 'item 3':4, 'item 4':2}
p = []
Subtotal = 0
tax_rate = 5.5 # 5.5%
while 1:
item = input(f'''
Enter the item you will purchase {list(D.keys())},
or Press "Done" if you want to finish.: ''')
if item.upper() == 'DONE':
... |
# What is your age? 15
# You are not old enough to legally drive.
# Or
# What is your age? 35
# You are old enough to legally drive.
age=input('what is your age?')
if int(age)<16:
print('You are not old enough to legally drive.')
else:
print('You are old enough to legally drive.')
|
length=input('length? ')
width=input('input? ')
area=int(length)*int(width)
gallons=round(float(area)/350)
if area%350 ==0:
gallons = round(float(area) / 350)
else:
gallons = round(float(area) / 350)+1
print('''You will need to purchase %d gallons of
paint to cover %d square feet.'''%(gallons,area))
... |
import random
def n():
while True:
a= raw_input("write something")
if a == "n":
a = random.randint(0,1)
if a == 1:
print "H"
else:
print "T"
elif a == 'b':
ab = int(raw_input("how many times?"))
lis = []
for x in xrange(ab):
a = random.randint(0,1)
lis.append(a)
print lis
n(... |
import random
def game():
secret_numb = random.randint(1, 10)
guesses = [];
while len(guesses) < 5:
try:
play_guess = int(input("What is your guess?"))
except ValueError:
print("{} is not a number".format(play_guess))
else:
if play_guess == secret_numb:
print("You got it!")... |
a = float(input("Enter a starting number: "))
r = float(input("Enter a common ratio: "))
i = 0
print("Geometric series starting with {} and with comman difference of {} is:\n".format(a, r))
l = [a * (pow(r,n)) for n in range(10)]
print(l)
sum(l) |
# Look for #IMPLEMENT tags in this file. These tags indicate what has
# to be implemented to complete the warehouse domain.
'''
Construct and return Tenner Grid CSP models.
'''
from cspbase import *
import itertools
def tenner_csp_model_1(initial_tenner_board):
'''Return a CSP object representing a ... |
'''
Copyright (c) 2010, Jeffrey Lipton (jil26@cornell.edu)
All rights reserved.
'''
from xml.etree.ElementTree import ElementTree , Element
from math import sqrt, pow
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = ... |
import random
def Check(i,j,k,tr):
if [i,j,k] in tr or [i,k,j] in tr or [k,i,j] in tr or [k,j,i] in tr or [j,i,k] in tr or [j,k,i] in tr:
return False
else:
return True
while True:
lst = random.sample(range(-30,30),30) #dimiourgia pinaka me mono thetikous kai arnitikous opos zitei... |
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
root = Tk()
root.title("Pandey Rocks")
def open():
global my_image
root.filename = filedialog.askopenfilename(initialdir="/gui/images", title="select a file",filetypes=(("png files", "*.png"), ("all files", "*.*")))... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 10:32:18 2020
@author: mohsi
"""
def highestValuePalindrome(s, n, k):
# form a n by n array
opt = [[0]*n for x in range(n)]
# initialize the diagnol
for row in range(n):
opt[row][row] = 1
# only go till row edge
for row... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 10:43:58 2020
@author: mohsi
"""
def searchRange(nums,target):
low = 0
high = len(nums)-1
result=[-1,-1]
while(low<=high):
middle = (high+low)//2
middle_l = middle-1
middle_r = middle+1
# thr... |
# Exercise 6: Rewrite the program that prompts the user for a list of
# numbers and prints out the maximum and minimum of the numbers at
# 8.16. EXERCISES 107
# the end when the user enters “done”. Write the program to store the
# numbers the user enters in a list and use the max() and min() functions to
# compute... |
#Exercise 2: Write another program that prompts for a list of numbers
#as above and at the end prints out both the maximum and minimum of
#the numbers instead of the average
max = None
min = None
while True:
str_number = input("enter a number: ")
if str_number == "done":
break
try:
... |
nums = [i for i in range(1, 6)]
# 数字映射
res = map(lambda x: x ** 2, nums)
print(res)
print(list(res))
# 字符串映射
names1 = ['jack', 'tom', 'lucy', 'ming']
res1 = map(lambda x: x + ' is super star', names1)
print(list(res1))
names2 = ['jack', 'tom', 'lucy', 'ming']
res2 = map(lambda x: x + ' is super star' if x == 'ming' ... |
# A simple password cracker script
from itertools import product
import string
import time
def cracker(password):
"""How long it will take to crack a given a password
Keyword arguments:
password: the password to crack
Returns: a list
"""
number_of_attempt = 0
characters = string.prin... |
def DPchange(money,coins):
mincoins = [0]*(money+1)
for m in range(1,money+1):
mincoins[m] = float('inf')
for i in range(len(coins)):
if m>=coins[i]:
numcoin = mincoins[m-coins[i]] + 1
if numcoin<mincoins[m]:
mincoins[m] = numc... |
def fractional_knapsack(capacity,weights,values):
items = [0]*capacity
value = 0
for k in range(len(weights)):
if capacity==0:
return value
index = 0
for i in range(len(weights)):
if(weights[i]>0 and (values[i]/weights[i])>(values[index]/weights[index])):
... |
from nltk.tokenize import word_tokenize
import string
#function to remove all punctuation from dataset text
def clean_doc(text):
clean_words= []
words = word_tokenize(text)
for word in words:
word = word.strip(string.punctuation)
if len(word)>=1 and word.isdigit()==False:
... |
if __name__=='__main__':
import time
import random
play_it=raw_input('do you want to play it.(\'y\'or\'n\')')
while play_it=='y':
c=raw_input('input a character:\n')
i=random.randint(0,2**32)%100
print 'please input number you guess:\n'
start=time.clock()
guess=i... |
"""
Obtain data via the RESTful restcountries.eu API
"""
import requests
from nobel_mongo import get_mongo_database
REST_EU_ROOT_URL = "http://restcountries.eu/rest/v1"
def rest_country_request(field="all", name=None, params=None):
"""
Make a URL for the `restcountries.eu` API and return a response
"""... |
from random import *
from math import *
import random
import time
def treasureHunt():
print("Ahoy, matey! Welcome to the Treasure Hunt!")
# Declare variables
distance = 0
foundTreasure = False
stepAmount = 0
# Explorer's coordinates
x, y = 15, 15
myLocation = (x, y)
#... |
#!/usr/bin/python
# gen_fat_fs.py
# Jeremy Singer
# 26 Feb 2017
## simple python script to create an example, empty FAT
## filesystem image, from scratch
image = 'example.img' # or use an argument from command-line?
# create (or overwrite) the file and start writing bytes (wb) into it
f = open(image, 'wb')
####... |
#Estructuras condicionales anidadas (SI – SINO - SI)
#Ejercicio 8: Confeccionar un programa que pida por teclado tres notas de un alumno, calcule el promedio e imprima alguno de estos mensajes:
"""
nota1 = float(input("Digite la primera nota: "))
nota2 = float(input("Digite la segunda nota: "))
nota3 = float(input... |
#Program Name: Operations
#Objective: We'll learn how aritmetical operations works
#Also, we'll see while and for loops
#Author:Brandon I. Pérez Sandoval
#Date: Jun 29 2019
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - 2
def mult(num1, num2):
return num1 * num2
def div(... |
#Program Name: Lists
#Objective: We'll see how list works in python
#Author:Brandon I. Pérez Sandoval
#Date: July 2nd 2019
#-------------------------------------------------------
import os
#-------------------------------------------------------
#Declaring a global list
#----------------------------------------------... |
# a breadth-first search function to find if within a network we know a doctor
from collections import deque
def person_is_doctor(name):
return name == 'jonny'
graph = {}
graph['you'] = ['alice', 'bob', 'claire']
graph['bob'] = ['anuj', 'peggy']
graph['alice'] = ['peggy']
graph['claire'] = ['thom', 'jonny']
... |
#!/usr/bin/python
import sys
# Take input from the standard input, split the line
# and output the item and the corresponding basket
# size it was found in
for line in sys.stdin:
line = line.strip()
items = line.split(' ')
# We don't want to output the basket size for each
# item found in the basket. ... |
# Problem 9:
# This problem was asked by Airbnb
"""
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
Follow-up: C... |
"""
Semi-unival tree:
0
/ \
1 0
/ \
1 0
/ \
1 1
The tree is said to be semi unival if one of its child subtree has same value as root value
"""
def count_semi_unival_subtrees(root):
total_count, is_unival = helper(root)
return total_count
def helper(root):
if root is None:
return 0, Fals... |
def alphabet_position(letter):
# returns the 0-based numerical position of that letter within the alphabet
ord_let = ord(letter.lower()) - 97
return ord_let
def rotate_character(char, rot):
#this fuction shifts the variable char by the variable rot number of times
shift_ = alphabet_po... |
import multiprocessing as mp
def powerOf(num):
return num**2
def my_func(x):
print("the square of", x, "is", x**2, "done by", mp.current_process().name)
def main():
print("cpu count: ", mp.cpu_count())
numbers = list(range(10,20))
print("numbers in list", numbers)
pool = mp.Pool(mp.cpu_coun... |
# def divide(a,b):
# try:
# return a/b
# except:
# return "Zero devision is meaningless"
def divide(a,b):
try:
return a/b
except ZeroDivisionError:
return "Zero devision is meaningless"
# except TypeError:
# return "write correct sytnax"
print(divide(1, 0)... |
correct_password = "python123"
name = input("Enter a name: ")
surname = input("Enter Surname: ")
password = input("Enter password: ")
while correct_password != password:
password = input("Wrong password! Enter again: ")
# virgüler ile stringler tanımlanabiliyor.
print("Hi", name, "you are logged in")
# % yüzde... |
import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(-5, 5)
y1 = xs**2
y2 = np.full(50, np.pi)
plt.plot(xs, y1, label='x^2')
plt.plot(xs, y2, label='Pi')
plt.fill_between(xs, np.max(y1), y1, color='b')
plt.fill_between(xs, y2, y1, color='w')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid()
plt.show()
|
import string
import random
def gen():
s1 = string.ascii_uppercase
#uppercase letters of A TO Z saved to s1
#print(s1)
s2 = string.ascii_lowercase
#lowercase letters of A TO Z saved to s2
#print(s2)
s3 = string.digits
#0 TO 9 saved to s3
#print(s3)
s4 = string.... |
# Andrew Sala
# 3B
with open('story.txt') as f:
story = f.readlines()
print('First line')
print(story[0])
print('Last line')
print(story[len(story)-1])
print('Even lines')
for i,j in enumerate(story):
if i % 2 != 0:
print(j)
print('Odd lines')
for i,j in enumerate(story):
if i ... |
# Andrew Sala
# RPS
import random
running = False
#used for spacing
def line():
print('\n-------------------\n')
#Class to generate cpu move
class Cpu:
rps = ['Rock', 'Paper', 'Scissors']
def __init__(self):
self.rps = Cpu.rps[random.randint(0, len(Cpu.rps)-1)]
self.flop = Cpu.f... |
import math
class Person:
def __init__(self, first_name):
self.first_name = first_name
#Getter functipn
@property
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('E... |
import re
text = input("Text: ")
def main(t):
nWords = countWords(t)
nLetters = countLetters(t)
L = nLetters/nWords * 100
# print(L)
# print(f'{nLetters} letter(s)')
# print(f'{nWords} word(s)')
nSentences = countSentences(text)
S = nSentences/nWords * 100
# print(S)
# print(f'... |
import sqlite3
def id_of():
file = open('id.txt', 'r')
id_txt = file.read()
file.close()
id = int(id_txt)
return id
def id_in(id):
id += 1
id_str = str(id)
file = open('id.txt', 'w')
file.write(id_str)
file.close()
def hello():
print('\nДобро пожаловать в программу по рабо... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 29 21:33:12 2014
@author: girish
"""
iteration = int(input())
for z in range(iteration):
word = input()
count=0
for x in range(len(word)-1):
if word[x] ==word[x+1]:
count+=1
print(count)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 11 17:01:39 2014
@author: girish
"""
iteration = int(input())
ans_list=[]
for i in range(iteration):
input()
no_of = int(input())
sum1=0
for j in range(no_of):
sum1+=int(input())
if(sum1 % no_of == 0):
ans_list.append("... |
__author__ = 'Girish'
import math
def find_devisors(number):
yield 1
for i in range(2,int(math.sqrt(number))+1):
if number%i==0:
yield i
yield number//i
def predicate(number):
memo=set()
def func(n):
num = number
for i in range(int(math.sqrt(num//n)))... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 22 21:21:31 2014
@author: girish
"""
def is_a_tree():
a,b = [ int(x) for x in input().split(" ") ]
li = []
for i in range(b):
j=0
node1,node2 = [int(y) for y in input().split(" ")]
if len(li) == 0 :
... |
from _heapq import heappush, heappop
def heapsort(data):
h=[]
for value in data:
heappush(h,value)
return [heappop(h) for i in range(len(h))]
x=heapsort([1,7,4,0,3,8,2,6])
print(x)
print(heapsort([1,7,4,0,3,8,2,6]))
|
from collections import deque
queue = deque ([1,2,3,4,5,6,7])
queue.appendleft(89)
queue.append(77)
print(queue)
print(type(queue))
print(type(deque))
|
from builtins import int
seat={1:'Empty',2:'Empty',3:'rahul',4:'Empty',5:'Empty',6:'Empty',7:'Empty',8:'Empty',9:'Empty',10:'Empty'}
''' shows empty seats '''
class TicketBooking:
# for Displaying Empty seats
def Show(self):
for i in seat:
if seat[i] ==str('Empty'):
#BookSeat()
... |
from Tkinter import *
import tkFileDialog,ttk
root = Tk()
def browsefunc():
filename = tkFileDialog.askopenfilename(title = "Select Query sequence file",filetypes = (("fasta files","*.fasta"),("all files","*.*")))
# pathlabel.config(text=filename)
# print (filename)
#Using try in case user types in un... |
# Manual unit testing
def test_sum():
assert sum([1, 2, 3]) == 6, "Should be 6"
if __name__ == "__main__":
test_sum()
print("Everything passed")
# In order to make better unit tests and instead of creating single input tests for our unit test, is better to use a Test Runner, in this case, unittest
import... |
import cv2
import pandas as pd
import emoji
def generate_letters():
img = cv2.imread('a.png', 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# apply thresholding to transform into binary image
# threshold(img, threshold, when it passes the threshold which value should it be assigned (white, 255) and ... |
""" (c) This file is part of the course
Mathematical Logic through Programming
by Gonczarowski and Nisan.
File name: code/predicates/util.py """
def __prefix_with_index_sequence_generator(prefix):
""" A generator for a sequence of the form 'z1', 'z2', 'z3', ..., where the
prefix 'z' is customiz... |
""" (c) This file is part of the course
Mathematical Logic through Programming
by Gonczarowski and Nisan.
File name: code/tests.py """
import time
def test_task_timed(max_testing_time, test_task, debug=False):
if debug:
print('Timing the execution of', test_task.__qualname__ + ':')
start_t... |
""" (c) This file is part of the course
Mathematical Logic through Programming
by Gonczarowski and Nisan.
File name: code/predicates/functions.py """
import copy
from itertools import combinations
from code.predicates.syntax import *
from code.predicates.semantics import *
from code.predicates.util import ... |
number=int(input())
hours=int(input())
salary_hour=float(input())
salary=hours*salary_hour
print("NUMBER = %d"%number)
print("SALARY = U$ %.2f"%salary)
|
R=float(input())
pi=3.14159
volume=4.0/3*pi*R**3
print("VOLUME = %.3f"%volume) |
cake=input('您买哪种蛋糕?[1]提拉米苏;[2]维也纳巧克力杏仁蛋糕');
cake1=12;cake2=15;price=0;
num=input("您需要买几个?");
if cake==1:
price=cake1*num;
elif cake==2:
price=cake2*num;
print("您总共需要付:"+price+'元钱。');
|
#!/usr/bin/env python
#-*- coding:utf8 -*-
import os
import os.path
def traverse(pathname):
for item in os.listdir(pathname):
fullitem = os.path.join(pathname,item)
print(fullitem)
if os.path.isdir(fullitem):
traverse(fullitem)
traverse("D:\GitHub")
|
#!/usr/bin/env python
#-*- coding:utf8 -*-
print("一个简单type创建类的例子".center(100,"*"))
#type(object_or_name, bases, dict)
#type里面有三个参数,第一个类名,第二个基类名,第三个是属性
User = type("User",(),{"name":"derek"})
my_obj = User()
print(my_obj.name) #derek
print(" 使用type创建类和方法 ".center(100,"*"))
#不但可以定义属性,还可以定义方法
def say(self): #必须... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/7/28 19:45
# filename: 10.序列中出现次数最多的元素.py
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
import threading,time
class Consumer(threading.Thread):
def __init__(self,cond,name):
#初始化
super(Consumer,self).__init__()
self.cond = cond
self.name = name
def run(self):
#确保先运行Seeker中的方法
time.sleep(1)
self.con... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/7/28 19:23
# filename: 08.查找两个字典的相同点.py
a = {
"x": 1,
"y": 2,
"z": 3
}
b = {
"w": 10,
"x": 11,
"y": 2
}
print(a.keys() & b.keys())
print(a.keys() - b.keys())
print(a.items() & b.items())
# 字典构造一个排除几个指定键的新字典
c = {key: a[... |
str = 'ABCDABC'
# 分割全部
print(str.split('B'))
# 输出内容:['A', 'CDA', 'C']
# 分割一次
print(str.split('B', 1))
# 输出内容:['A', 'CDABC']
|
import math
#特征抽取
aim_film=[2,1,3,2,5]
sample_films_name=['《坏人家族》','《非洲攻略》','《阿龙》']
sample_films=[[1,3,2,4,1],[3,1,2,1,3],[1,2,1,3,4]]
#计算距离
dist_list=[]
min_dist=float('inf')
for row in sample_films: #遍历其余电影样本
sum_temp=0 #每行清零
for i in range(len(row)): #遍历每一条特征分
sum_temp+=(aim_film[i]-row[i])... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/15 2:54
# filename: getattr和setattr.py
class Rectangle:
def __init__(self, name, age):
self.name = name
self.age = age
def __setattr__(self, key, value):
# print("--------设置{}属性-----".format(key))
if key =... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# 计算圆面积的函数
import math
result = lambda r: math.pi * r * r
r = 10
print(result(r))
# result1 = lambda [arg1,[arg2,....argn] : expression
bookinfo = [('不一样的卡梅拉', 22.50, 120), ('零基础学Android', 65.10, 85), ('摆渡人', 23.40, 130), ('福尔摩斯探案', 20.50, 110)]
print('爬取到的商品名称:\n', bookin... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
number = range(-5, 5)
print(list(number))
filter1 = filter(lambda x: x > 0, list(number))
print(list(filter1))
list2 = [x for x in number if x > 0]
print(list2)
string = filter(lambda x: x != "h", "hujianli")
print(list(string))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'xiaojian'
import pymysql
def create_table():
db = pymysql.connect('localhost', 'root', 'admin#123', 'test')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在就删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE"... |
#成员运算符
team=['乔丹','邓肯','科比','小小','詹姆斯','韦德','奥拉朱旺','哈登']
print('这是一支梦之队:',team)
#做梦的人是“小小”
me='小小'
if me in team:
print(me,'是这只球队的成员!')
else:
print(me,'不是这只球队的成员!')
#做梦的换做“牛牛”
me='牛牛'
if me in team:
print(me,'是这只球队的成员!')
else:
print(me,'不是这只球队的成员!')
|
#finally子句示例
try:
x=input("输入0-3尝试捕获异常:")
if x not in ['0','1','2','3']:
print("本次没有发生异常。程序结束。")
import sys
sys.exit(0)
else:
triger=int(x)
if triger==0:
2/0
if triger==1:
int("a")
if triger==2:
'2'/'1'
print... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/5/18 7:25
# filename: 实例方法test.py
class Animal(object):
'''
定义动物类
'''
def __init__(self, age, sex=1, weight=0.0):
# 定义实例变量
self.age = age
self.sex = sex
self.weight = weight
def eat(self):
... |
#移动示例
import time
from tkinter import*
window=Tk() #建立主窗体
canvas=Canvas(window,width=500,height=500) #建立一个画布对象canvas
canvas.pack()
#建立多边形,顶点坐标(x1,y1,x2,y2,x3,y3)
canvas.create_polygon(10,10,10,60,50,35,fill='red') #图形编号为1,以后的图形编号顺序类推
def draw_one_frame():
canvas.move(1,5,0) #移动1号对象,x方向移动5像素,y方向... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
'''
线程中的数据是可以共享的
'''
from threading import Thread
g_num = 100
def plus():
print("-----子线程1开始-----")
global g_num
g_num += 50
print("g_num is %d " % g_num)
print("------子线程1结束-----")
def minus():
print("-----子线程2开始-----")
global g_num
g_num -... |
#引入knn算法
from knn_simple import knn
#回归计算
def regression(knn_value):
"""knn回归计算,knn_value为k最近邻对应的样本值"""
return sum(knn_value)/len(knn_value)
#目标特征值
aim=[1,4,5,'r'] #'r'表示待求的值
#样本特征值及样本值
sample=[[1,5,2,280],
[1,1,1,20],
[1,3,2,210],
[0,4,4,360],
[1,5,3,320],
[0,3... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/15 13:07
# filename: 与序列相关的特殊方法.py
def check_key(key):
'''
该函数将会负责检查序列的索引,该索引必须是整数值,否则引发TypeError
且程序要求索引必须为非负整数,否则引发IndexError
'''
if not isinstance(key, int):
raise TypeError('索引值必须是整数')
if key < 0:
rais... |
#8.1triangle.py
a=int(input('输入三角形的边长a:'))
b=int(input('输入三角形的边长b:'))
c=int(input('输入三角形的边长c:'))
if a+b>c and b+c>a and a+c>b:
print('可以组成三角形')
if a==b or b==c or a==c:
print('等腰三角形')
if a==b and b==c:
print('等边三角形')
else:
print('不能组成三角形')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.