text
stringlengths
37
1.41M
# count number of vowels in a string # function: # ========= # name: isAVowel # parameter: character: string # return type: boolean # pseudo code: # ============ # if character is 'a' or 'e' or 'i' or 'o' or 'u' # return true # else # return false # alternative pseudo code: # ======================== # return t...
# sort vs sorted my_list = [1,5,3,7,2] #mutable, can change them my_dict = {'car':4,'dog':2,'add':3,'bee':1} #mutable my_tuple = ('d','c','e','a','b') #immutable my_string = 'python' #immutable # lists # sort - doesn't return anything, just sorts the list # sorted - function, returnd new object that has been sorted ...
class Queue: class Node: def __init__(self, data): self.data = data self.next = None def __init__(self): self.first = None self.last = None def add(self, item): new_node = self.Node(item) if self.last: self.last.next = new_node ...
import sqlite3 file_title = "Test" def create_db_and_table(): conn = sqlite3.connect("%smydatabase.db"%file_title) cursor = conn.cursor() sql = "CREATE TABLE file_title (Block_Size int, Resident_Strategy text, Social_Affinity int, Resident_Density int, Negative_Impact int, Ticks int, Mortgage_Buyout_Ratio...
a=[3,4,5,5,6,7,8] a.clear() print(a) a=[3,4,5,5,6,7,8] del(a) print(a) #copy a=[3,4,5,5,6,7,8] b=a.copy() a.append(9) print(a) print(b) #direct assignment a=[3,4,5,5,6,7,8] b=a a.append(1) print(a) print(b) #list to tuple a=[1,2,3,4,5,6,7,8,9] b=tuple(a) print(b) #list to set a=[1,2,3,4,5,6,7,8,9...
def choice(): front=0 rear=0 print('''Operations Available: 1.Stack 2.Queue 3.Linkedlist''') a=input("Enter the choice you need to perform: ") items=[] front=0 rear=0 if a=='1': Stack() elif a=='2': ...
#!/usr/bin/python ## @package p002 # Script for Project Euler, Problem 2 # # Calculates the sum of all even Fibonacci numbers less than four # million from __future__ import print_function, division # Executable script if __name__ == "__main__": # Parameters ## Maximum Fibonacci number nmax = 400...
import numpy import pygame class Segment: def __init__(self, p0, p1): self.p0 = p0 self.p1 = p1 def __str__(self): return "Segment(({0}, {1}), ({2}, {3}))".format( self.p0[0], self.p0[1], self.p1[0], self.p1[1] ) def inters...
""" SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order spy_game([1,2,4,0,0,7,5]) --> True spy_game([1,0,2,4,0,5,7]) --> True spy_game([1,7,2,0,4,5,0]) --> False In [ ]: def spy_game(nums): pass In [ ]: # Check spy_game([1,2,4,0,0,7,5]) In [ ]: # Check spy_ga...
def eggs(someparameter): someparameter.append("hello") spam =[1,2,3] eggs(spam) print(spam) #imstead of reference the existing list, you can copy it. import copy spam=['A','B','C',1,2] cheese=copy.deepcopy(spam) print(spam) print(cheese) cheese[1]=42 print(spam) print(cheese)
''' ask the name and guess the number it has five trials ''' import random print("Hello what is your name?") name=input() name=name.capitalize() # change the name to be first letter to be upper no matter what people input. secretNumber = random.randint(1,20) print("Well, "+name+" I am thiking of number between 1 aned 2...
""" #1 import difflib file1 = "myFile1.txt" file2 = "myFile3.txt" diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines()) differences=''.join(diff) print(differences) if differences =='': print ('no differences') else: print('there is an update') print('update is ') print('') print...
def myfuncstr(x): result ="" x=x.lower() for i in range(1,len(x)+1): if i%2==0: #print("2",i) result+=x[i-1].upper() else: #print(i) result+=x[i-1] return result print(myfuncstr("TheBeautifulDreamiscomingTrue"))
#!/usr/bin/env python3 #https://pythex.org/ #without regex, finind number: def isPhoneNumber(text): if len(text) !=12: return False for i in range(0,3): if not text[i].isdecimal(): return False if text[3] != '-': return False for i in range(4,7): if not te...
#!/usr/bin/env python # -*- coding:utf-8 -*- from numpy import * import matplotlib.pylab as plt import sympy data = array([ [1.2, 3.6], [2.3, 4.6], [1.8, 7.6], [5.4, 15.8], ]) def plotting(res): fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(array(data[:, 0]), arra...
import turtle import random """ Homework 9- Recursion and Fractals Authors: Abigail Santiago and Natnael Mulat Time Spent: 4 hours """ def recursive_delete(str_, char): """ This function deletes the character char in the parameter str_. Parameters: str_- A string of an...
# https://open.kattis.com/problems/aaah text = input() text1 = input() if len(text) < len(text1): print("no") else: print("go")
# https://leetcode.com/problems/median-of-two-sorted-arrays/ def merge_lists(l1, l2): merge = [] len_1 = len(l1) len_2 = len(l2) if len_1 > len_2: big_list, small_list = l1, l2 else: big_list, small_list = l2, l1 big = small = 0 while...
def factorial(num): if num == 0 or num == 1: return 1 return num * factorial(num-1) print("5 Factorial: ", factorial(5)) # Binary Search (Non-recursive) nums = [3, 12, 14, 16, 19, 23] def binary_search(target, num_list): list_len = len(num_list) low = 0 high = list_len - 1 if list_le...
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ def is_palindrome(self, s): start, end = 0, len(s) - 1 while start <= end: if s[start] != s[end]: return False start +...
# Aula 15 Loops - While contador = 0 while contador < 5: print("Contador: ", contador) contador += 1 else: print("Fim do while - contador: ", contador) pessoas = [] x = 0 while x < 4 and "Julia" not in pessoas: nome = input("Qual o seu nome? ") pessoas.append(nome) print(pessoas) x +=1 el...
# Condicionais If Else Elif parte 01 numero = input("Digite sua idade: ") if float(numero) == 18 : print("O número é 18") elif float(numero) > 18: print("Você é maior de idade") elif float(numero) < 18: print("Você é menor de idade") else: print("Essa não é uma idade válida") idade = float(input("Digi...
# name = "ada lovelace" # print(name.title()) # print(name.upper()) # print(name.lower()) # first_name = "ada" # last_name = "lovelace" # full_name = f"{first_name} {last_name}" # #full_name = "{} {}".format(first_name, last_name) # #print(full_name.title()) # print(f"Hello, {full_name.title()}!") message = "One of P...
# 9. Reverso do número. Faça uma função que retorne o reverso de um # número inteiro informado. Por exemplo: 127 -> 721. lista = [] palavra = input('Palavra ou Número: ') tamanho = len(palavra ) def reverso(nome): for i in range (tamanho-1,-1,-1): lista.append(palavra[i]) print('\n', lista, '\n') ...
import typing import os from pathlib import Path import fire import numpy as np from sklearn.datasets import make_regression def make_skl_dataset(n = 10000, p = 100, len_y = 1000, x_rank=1, noise=.1, train_split = .6, valid_split = .2): """ Generates a synthetic dataset suitable for training and assessing a TEAs ...
# A variable is a container for a value, which can be of various types ''' This is a multiline comment or docstring (used to define a functions purpose) can be single or double quotes ''' """ VARIABLE RULES: - Variable names are case sensitive (name and NAME are different variables) - Must start with a letter or...
#!/usr/bin/env python3 import psycopg2 DBNAME = "news" def get_data(query): """ fetch data from database """ db = psycopg2.connect(database=DBNAME) c = db.cursor() c.execute(query) data = c.fetchall() db.close() return data def list_popular_articles(): """ display the popular artic...
from cs50 import get_int cardnumber = -1 while cardnumber<0: cardnumber = get_int("Number: ") total = 0 ae = 0 digit = 0 mc = 0 visa = 0 i = 0 while cardnumber>0: digit += 1 if i % 2 == 0: remainder = cardnumber % 10 total += remainder else: remainder = 2*(c...
import copy from typing import Dict, Any, List, Set, TypeVar, cast #: :obj:`int` : #: Maximum depth to which dictionaries are merged MAX_RECURSION_DEPTH: int = 8 def dict_deep_update( target: Dict[object, object], source: Dict[object, object], recursion_depth: int = 0 ): """Simple function to deep-update tar...
str_bill = "item:apples,quantity:4,price:1.50\n" def calculate_bill(str_input): split_str = str_input.split(",") quantity = float(split_str[1].split(":")[1]) price = float(split_str[2].split(":")[1]) return quantity * price calculate_bill(str_bill) items = ["item:apples,quantity:4,price:1.50\n", "ite...
#!/usr/bin/env python def is_prime(n): is_prime = True def is_divisible(n,divisor): if n<2*divisor: return False if n%divisor==0: return True else: divisor += 1 return is_divisible(n,divisor) if is_divisible(n,divisor=2): is_prime=False return ...
# Напишите программу для пересчёта величины временного интервала, # заданного в минутах, в величину, выраженную в часах и минутах. m = int(input()) print( m, 'мин -', 'это', m//60, 'час', m%60, 'минут.' )
#На вход программе подается строка текста # – название футбольной команды. Напишите программу, # которая повторяет ее на экране со словами « - чемпион!» (без кавычек). name = input() print(name, '- чемпион!')
a = int(input()) b = int(input()) x1 = (a + b)**2 x2 = a**2 + b**2 print( 'Квадрат суммы', a, 'и', b, 'равен', x1 ) print( 'Сумма квадратов', a, 'и', b, 'равна', x2 )
#В популярном сериале «Остаться в живых» использовалась последовательность чисел 4 8 15 16 23 42, # которая принесла героям удачу и помогла сорвать джекпот в лотерее. # Напишите программу, которая выводит данную последовательность чисел с одним пробелом между ними. print('4', '8','15','16','23','42')
string = input('Give a brief summary about anything: ') for char in string: if char == 'A': string = string.replace('A','4') elif char == 'E': string = string.replace('E', '3') elif char == 'G': string = string.replace('G', '6') elif char == 'I': string = string.replace(...
day = int(input('Day (0-6)? ')) if day >= 1 and day <= 5: print('Go to work') elif day == 0 or 6: print('Sleep in')
hex_str = 0 def hex_to_dec(hex_str): hex_dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'a': 10 , 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15} user_input = input("Enter a hexadecimal value you would like to convert to a decimal: ") length = len(user_input) -1 ...
import sqlite3 connection = sqlite3.connect("PropertyResale.db") user = """ CREATE TABLE User ( UserID TEXT UNIQUE, Name TEXT, Contact INTEGER, Email TEXT, PRIMARY KEY("UserID") ) """ connection.execute(user) Property = """ CREATE TABLE Property ( PropertyID TEXT UNIQUE, Address TEXT, Postal INTEGER, TotalArea INTEG...
# -*- coding: utf-8 -*- """ Created on Tue Jan 9 19:44:11 2018 @author: navya """ import re; T=int(input()) for i in range(T): print (re.match(r'(.)\d )) x=re.match(r')
# -*- coding: utf-8 -*- """ Created on Sun Jan 7 18:36:50 2018 @author: navya """ N=int(input()); from collections import OrderedDict; itemnames=OrderedDict(); for i in range(N): item, space, quantity = input().rpartition(' ') itemnames[item] = itemnames.get(item, 0) + int(quantity) for item, qu...
# -*- coding: utf-8 -*- """ Created on Sat Jan 6 12:34:49 2018 @author: navya """ N=int(input()); fibSer=[] for i in range(N): if (i==0): fibSer.append(0); elif (i==1): fibSer.append(1); else: fibSer.append(fibSer[i-2]+fibSer[i-1]); print(list(map(lambda z: z**...
# -*- coding: utf-8 -*- """ Created on Fri Jan 5 20:36:03 2018 @author: navya """ import itertools as it; s=input().split(); l= list((it.permutations(sorted(s[0]),int(s[1])))); for i in l: print (*[''.join(i)])
# PS-35 Ask user to enter 10 element in the list and find even and odd from the list def check_even(n): if n % 2 == 0: return True else: return False li=[] li_len = 10 c=0 print("Enter 10 element to the list-") while c != li_len: try: no = int(input("Enter element no.{} :".format(...
# PS-18 WAP to print an Identity Matrix ''' ex- Enter no: 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ''' no = int(input("Enter no: ")) for i in range(0,no): for j in range(0,no): if i == j: print(" {} ".format(1),end="") else: print(" {} ".format(0),end="") print()
# PS-48 WAP to accept string from user and a single character. Display how many times given characters occurs in a given a given string def count_single_character_in_string(str,ch): counter = 0 for c in str: if c == ch: counter = counter + 1 return counter str = input("Enter your strin...
# PS-33 WAP to read list of words and return the length of the longest one def find_longest_word_in_li(li): longest_element = '' for element in li: if len(element) >= len(longest_element): longest_element = element return longest_element li = ['Apple','Banana','Orange','Pear','Cherry'...
# PS-10 WAP to print odd numbers within a given range try: print("Enter range -") start = int(input("Start: ")) end = 0 while end < start: print("End no. should be greater than start no.") end = int(input("End: ")) print("\nOdd numbers in a range {} to {}:".format(start,end)) ...
# PS-02 WAP to exchange the values of two numbers without using a temporary variable n1 = 10 n2 = 6 print("Before exchange:") print("n1={} n2={}".format(n1,n2)) #exchangng the values of two numbers without using a temporary variable n1 = n1 + n2 n2 = n1 - n2 n1 = n1 - n2 print("After exchange:") print("n1={} n2={}"...
# PS-04 WAP to accept radius of circle and calculate area and circumference of circle r = float(input("Enter radius of circle: ")) #Aera of circle area = 3.14 * r * r #Circumference of circle circum = 2 * 3.14 * r print("Area:",area) print("Circumference:",circum)
# PS-06 WAP to take marks of 5 subject and display the grade c = 0 while c != 5: try: marks = int(input("Enter subject-{} marks:".format(c+1))) if marks >= 0 and marks <=100: c = c + 1 if marks >= 90 and marks <= 100: print("Subject-{} grade: A".format(c)) ...
chances = 2 def math_set(): math1_solution = '2' num_of_try = 0 while num_of_try < chances: math1_input = raw_input('1. 1 + 1 = ? ') if math1_input == math1_solution: print 'Your solution is correct.' break else: if num_of_try == 0: ...
"""Unicorn position tracker.""" import json class Unicorn(object): """A unicorn.""" def __init__(self, name, color, fave_food, position='barn'): """Create a new unicorn.""" self.name = name self.color = color self.fave_food = fave_food self.position = position def...
#!/usr/bin/env python3 import sys args = sys.argv[1:] unsorted_numbers = [] if len(args): for arg in args: x = float(arg) unsorted_numbers.append(x) else: s = input("Enter a number (blank to quit): ") while len(s) > 0: x = float(s) unsorted_numbers.append(x) s = in...
# Universidade Estadual do Rio Grande do Norte - UERN # Curso de Ciências da Computação # Algoritmo de criptografia - Cifra de cesar # Alunos: Matheus Diogenes e Francisco Clementino # Esta função é usada para cifrar/decifrar mensagem. class SimpleSubstitution: def __init__(self): self.p_alphabet = 'ABC...
#Retorno de valores def soma(x,y): num = x*y return num print("teste") print (soma(10,20)) #def soma(x,y): # if(x*y==200): # return True # else: # return False #print (soma(10,20))
# Escreva uma função que aceite Strings e calcule a # quantidade de letras em mauisculas e minúsculas que a String possui. def func(x): mi=0 #DEFINIR AS DUAS VARIAVEIS Q SERAO INCREMENTADAS ma=0 for k, v in enumerate(x):# ESSE FOR ENUMERATE FAZ RODAR TODAS AS POSICOES DA STRING ATE O SEU FINAL DANDO O ...
cont =[] lista = [] maior= menor =0 while True: nome = input("digite seu nome:") peso = int(input("digite seu peso:")) res = input("Deseja continuar? ").lstrip().upper()[0] lista.append(nome) lista.append(peso) if len(cont)==0: maior = menor = lista[1] else: if lista[1]>maio...
guests = ['Ben', 'Jack', 'Tom'] print('I can only invite two of you.') guests.insert(0, 'John') guests.insert(2, 'David') guests.append('Leon') pop_guest1 = guests.pop() print('Sorry ' + pop_guest1 + ', you are not invited.') pop_guest2 = guests.pop() print('Sorry ' + pop_guest2 + ', you are not invited.') pop_guest...
# -*- coding: utf-8 -*- # Conventions are according to NumPy Docstring. """ Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The...
# -*- coding: utf-8 -*- # Conventions are according to NumPy Docstring. """ The Fibonacci sequence is defined by the recurrence relation: F_n = F_{n−1} + F_{n−2}, where F_1 = 1 and F_2 = 1. Hence the first 12 terms will be: F_1 = 1 F_2 = 1 F_3 = 2 F_4 = 3 F_5 = 5 F_6 = 8 F_7 = 13 F_8 = 21 F_9 = 34 F_10 = 55 F_11 = 8...
""" 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? """ import time import math def is_prime(n): """ Assume that the input is larger than 1. """ ...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ import time import math def is_prime(n): """ Assume that the input is larger than 1. """ if (n == 2): return True elif (n % 2 == 0 or n <= 1): ...
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers. """ import time from itertools import product def isPalindrome(number): number = str(number) reve...
#!/usr/bin/env python # coding: utf-8 # # 1. Stemming # # Stemming works fairly well in most of the cases but unfortunately English has so many exceptions where a more sophisticated process is required. # # SpaCy dosen't include stemming, it uses lemmatization instead. # # Stemming is basically removes the suffixes...
import random money = 100 #Write your game of chance functions here def headsOrTails(choice, bet): toss = '' num = random.randint(1, 2) if(num ==1): toss = 'Heads' else: toss = 'Tails' global money if(money < bet): print('You don\'t have enough cash. Maybe you should call it a night and com...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
from statistics import mean, median,variance,stdev import math import sys def char_type(ch): if ch.islower(): return "lower" if ch.isupper(): return "upper" if ch.isdigit(): return "digit" return ch def randomness(string): counts = {} types = [] for i in range(len(...
v=str(input("enter the letter to check it is a vowel or not :")) x=("AEIOUaeiou") if v in x: print("it is a vowel") else: print("it is not a vowel")
# Rotate an array of n elements to the right by k steps. # # For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums ...
import random def getDiceRoll(): print('please input number of dice') return input() def getDiceSides(): print('input type of dice') return input() def checkValid(num): if num.isdigit(): return True else: return False def rollDice(num, sides): count = 0 min = 1 max = int(sides) while (count < max): ...
""" module docstring """ import math def sin_(number): """ function docstring """ sine = 0 i = 0 while True: max_sine = sine sine += ((-1) ** (i)) * ((number ** (2 * i + 1)) / math.factorial(2 * i + 1)) if (max_sine - sine) < 1e-10: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 19 17:09:04 2019 @author: aishee """ from collections import Counter def removechar(s1,s2): dict1=Counter(s1) dict2=Counter(s2) print(dict1) key1=dict1.keys() key2=dict2.keys() print(key1) count1=len(key1) count2=len(...
import csv class Time_Entry(): def __init__(self): """Initializes Time_Entry class. All fields are either an empty string or a 0. """ self.date = "" self.title = "" self.time_spent = 0 self.notes = "" def set_date(self, date): """Sets date fi...
# if cold outside # wear a coat # go to class # if temp <= 50 # wear a coat # go to class ##x = 0 ##y = 0 ## # if x < 0: ## print("x is negative") # elif x > 0: ## print("x is positive") # else: ## print("x is zero") ## # print("Bye") # dual alternative decision structure # if condition: # stmt # stm...
import classContact def main(): try: friends_file = open("contactsLab5.txt", 'r') friend_list = [] name = friends_file.readline() while name != "": name = name.rstrip('\n') birthdate = friends_file.readline().rstrip('\n') a...
# Chapter 2.8 More about Data Output # Suppress print functions ending newline print('One') print('Two') print('Three') print() #On same line print('One', end=' ') print('Two', end=' ') print('Three') print() ## ###Same line no spaces tho ##print('One', end='') ##print('Two', end='') ##print('Three') ##print() ## ...
class Friend: def __init__(self, name, age, food): self.__name = name self.__age = age self.__food = food def set_name(self, name): self.__name = name def set_age(self, age): self.__age = age def set_food(self, food): self.__food = food ...
# Pulling libraries import random import math def main(): times = int(input("How many times? ")) lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for i in range(times): rand_num = get_random_num(lower, upper) print("The squre root of", rand_num, ...
# chapter 7 reboot 5/2/21 Sunday to beat Lab 4 to death # replay lectures from 4/8 Thursday def main(): # 7.4 Searching Lists with while loop and in operator item_numbers = ['V475', 'F978', 'Q143', 'R688'] item = input('Enter item number: ') stock = False i = 0 while not stock and i!= len...
############################################################### # Yolanda Gunter # Lab 4 # My program uses decisions, repetition, functions, files, lists # and exception handling that will get the input from a file to # run program that asks User for current date, reads a contact file # list that contains...
def main(): # This is calling the function # Read two integers x = int(input("Enter and interger: ")) y = int(input("Enter and interger: ")) add_numbers(x, y) ####################################################### # Function name: add numbers # Purpose: This function displays the sum # ...
## Study of Chapter 6 Files and Exeptions ## Better late than never. I will do much better on this Exam 2 ## than I did on Exam 1. Conquer this and RULE my mind. # This program reads and displays the contents of # of the prophets.txt file def main(): # Open a file named prophets.txt. infile = open...
## Study of Chapter 6 Files and Exeptions ## Better late than never. I will do much better on this Exam 2 ## than I did on Exam 1. Conquer this and RULE my mind. # This program reads the contents of # of the prophets.txt file one line at a time def main(): # Open a file named prophets.txt. infile ...
class Students(object): def __init__(self,name,score): self.name= name self.score= score def print_score(self): print('%s: %s' % (self.name, self.score)) bart = Students('Bart Simpson', 59) lisa = Students('Lisa Simpson',87) bart.print_score() lisa.print_score() print(bart.name) print(...
#启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。我们先准备好程序: #python -m pdb 2.3.pdb.py s= '0' n=int(s) print(10/n) #以参数-m pdb启动后,pdb定位到下一步要执行的代码-> s = '0'。输入命令l来查看代码: #输入命令n可以单步执行代码: #任何时候都可以输入命令p 变量名来查看变量: #输入命令q结束调试,退出程序: #pdb.set_trace() #这个方法也是用pdb,但是不需要单步执行,我们只需要import pdb, # 然后,在可能出错的地方放一个pdb.set_trace(),就可以设置一个断点: impor...
''' def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax print(calc_sum(1,2,3,4)) def lazy_sum(*args): def sum(): ax=0 for n in args: ax =ax + n return ax return sum f=lazy_sum(1,2,3,4,5) f1=lazy_sum(1,2,3,4,5) print(f()) print(f==f1) ''' '''...
#操作图像 from PIL import Image #在当前路径下打开一个jpg图像文件 im=Image.open('1.jpg') #im.show() w,h=im.size#获得图像尺寸 print("Original image size: %sx%s" % (w,h)) im.thumbnail((w*2,h*2))#放大两倍 print('Resize image to: %sx%s' % (w*2,h*2)) im.save('thumbnail.jpg','png')#把放大后的图片以png的格式保存 from PIL import Image,ImageFilter im2=im.filter(Image...
''' class Student(object): pass s=Student() s.name='zhangzhonghua'# 动态给实例绑定一个属性 print(s.name) #尝试绑定一个方法 def set_age(self,age):#定义一个函数作为实例方法 self.age=age from types import MethodType s.set_age=MethodType(set_age,s)# 给实例绑定一个方法 s.set_age(25)# 调用实例方法 print(s.age)# 测试结果 #为了给所有实例都绑定方法,可以给class绑定方法 def set_score...
#如果不捕获错误,自然可以让Python解释器来打印出错误堆栈,但程序也被结束了。 # 既然我们能捕获错误,就可以把错误堆栈打印出来,然后分析错误原因,同时,让程序继续执行下去。 #Python内置的logging模块可以非常容易地记录错误信息: import logging def foo(s): return 10/int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) main() print('END')...
from functools import reduce def str2num(s): return int(s) def calc(exp): ss = exp.split('+') ns=map(str2num,ss) return reduce(lambda acc,x:acc +x , ns) def main(): try: r=calc('100+200+345') print('100+200+345 =',r) e=calc('99+88+7.6') print('99+88+7.6=',r) exc...
#凡是用print()来辅助查看的地方,都可以用断言(assert)来替代: def foo(s): n=int(s) assert n !=0, 'n is zero!' return 10/n #assert的意思是,表达式n != 0应该是True, # 否则,根据程序运行的逻辑,后面的代码肯定会出错。 #如果断言失败,assert语句本身就会抛出AssertionError: def main(): foo('0') main()
# -*- coding: utf-8 -*- """ Created on Sat Jan 20 22:35:14 2018 @author: Min Joon So, Shailesh Patro Blockchain wk1 assignment """ class Node: ''' class node for doubly linked list ''' def __init__(self,key,value): self.key = key self.value = value self.next = None...
n=int(input()) for i in range(n,0,-1): print(" "*(i-1)+"*"*(n-i+1)) for j in range(n,1,-1): print(" "*(n-j+1)+"*"*(j-1))
n = int(input()) li = [] for i in range(n): age,name = input().split() li.append((int(age),name,i)) li2 = sorted(li,key = lambda li: (li[0],li[2])) for (age,name,i) in li2: print(age,name)
def paper(a): if a == n: return 1 if a > n: return 0 return paper(a+10) + (2*paper(a+20)) t = int(input()) for tt in range(1,t+1): n = int(input()) ans = paper(0) print("#{} {}".format(tt,ans))
li = [1,5,8,14] total = [] for i in range(1<<len(li)): print("@",i) sub = [] for j in range(len(li)): if i&(1<<j): sub.append(li[j]) print("##",sub) total.append(sub) print(total)
import math from math import cos, sin, sqrt, asin from random import randint, uniform def mini_menu(): """Goin' the distance's mini main menu is a REPL and allows the user to call functions""" print #asks user for input user_choice = int(raw_input("Choose your menu item --> ")) ...
def tamanho_json(json): """ OBTÉM O TAMANHO DO JSON. # Arguments json: - Required: Json o qual será obtido o tamanho (Dict) # Returns """ try: return len(json.keys()) except Exception as ex: print(ex) return None def ...
import hashlib choice = int(raw_input("1. Image file \n 2. Audio/Video file ")) org_file = raw_input("Please enter file name 1 : ") new_file = raw_input("Please enter file name 2 : ") if(choice==1): org_hash = hashlib.md5(open(org_file,'r').read()).hexdigest() print "MD5 hash of original file : " + str(org_hash)...