text
stringlengths
37
1.41M
import sys import random # matrix = [ # [1,2], # [3,4], # [5,6], # ] # tony = [[row[i] for row in matrix] for i in range(2)] # print(tony) # points = random.sample([range(1,7),range(1,7)],3) # print(points) #losing_condtion= [[x,y],[y,z],[z,x]] losing_condition = [ [[x,y] for x in range(1,7) for y in ra...
from General_stack import Stack def decimal_binary(num): s = Stack() while num>0: remainder = num % 2 s.push(remainder) num = num//2 bin_num ="" while not s.is_empty(): bin_num+=str(s.pop()) return bin_num print(decimal_binary(242)) ...
def remove_negative(lst): result = [] for elem in lst: if elem > 0: result.append(elem) return result l = [1, 2, 3, 4, -10, 20, 0, -100] print(remove_negative(l))
#print("Day 1") #print("Day 2") #print("Day 3") #print("Day 4") #print("Day 5") #print("Day 6") #print("Day 7") #print("Day 8") #print("Day 9") #print("Day 10") #for i in range(1,11): #print("Day {}".format(i)) for num in range (1,11): print("Day {}".format(num))
class Player: name = '' job = '' health = 0 attack = 0 speed = 0 # Setters def set_name(self, n): self.name = n def set_health(self, h): self.health = h # Getters def get_name(self): return self.name def get_job(self): return self.job def get_health(self): return self.health def get_attack(self):...
# Collin Pearce 0% WA class point: def __init__(self,x,y): self.x = x self.y = y def __str__(self): return str(self.x) + ',' + str(self.y) def __repr__(self): return str(self.x) + ',' + str(self.y) def ccw(A,B,C): return (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(...
from tkinter import * def main(): result = "NULL"; num_entries = 0; def closest_prime(num): #checking above numU = num; numL = num; go =1; while(go):#proceed if prime not find numU = numU+1; go = prime_true(numU); go =1; ...
import re pattern = re.compile('apil') r = pattern.search('kapilisacheaterandheisafool') print(r.group(1)) """ This is about regular expressions: re.match('xyz', string) --- this will try to match the pattern at the start of string .group(0) will give the searched pattern ...
class member: count = 0 def __init__(self,name,age): self.name = name self.age = age member.count+=1 def tell(self): print("Name - {}, Age - {}".format(self.name, self.age), end=" ") class student(member): def __init__(self, name, age, marks): member.__init__(se...
#!/usr/bin/env python3 """ Example of how bodies interact with each other. For a body to be able to move it needs to have joints. In this example, the "robot" is a red ball with X and Y slide joints (and a Z slide joint that isn't controlled). On the floor, there's a cylinder with X and Y slide joints, so it can be pus...
import random import json quotes = [ "Ecoutez-moi, Monsieur Shakespeare, nous avons beau être ou ne pas être, nous sommes !", "On doit pouvoir choisir entre s'écouter parler et se faire entendre." ] # Read values from a JSON file def read_value_from_json(): values = [] with open('characters.json') as f: ...
import math #This script will take two points and calcuate the distance between them. #Gather inputs x1 = 1 y1 = 1 x2 = 4 y2 = 5 #Find the distance between point 1 and point 2.
def createRange1(x): outSeq = [] for c in range(0,x): outSeq.append(c % 3 + 1) return outSeq def createRange2(x): outSeq = [] c = 0 while x > c: outSeq.append(c % 3 + 1) print(c) c = c + 1 ##THIS IS THE LINE REFERENCED BELOW return outSeq def multiplySeq(x,...
myList = [] # This creates and empty list Cities = ["Hattiesburg, MS", "Irvine, CA", "Columbia, SC", "Calgary, AB"] ages = [23,25,45,11,34, 56] #my Map function to add a number to everyitem in a list def addnList(myList, n): newList = [] for number in myList: newList.append(number + n) return n...
x = 5 y = 7 if (x > y): print "x is bigger" else: if (x == y): print "they are equal" else: print "y is bigger" print "Done"
import math #inputs x1 = 3 y1 = 4 x2 = 6 y2 = 8 #logic #find the difference between the x values (xd) #find the difference beteen the y values (yd) #find the distance between the points #These two are equivalent statements that do the same thing choose one distance = (xd**2 + yd**2) ** 0.5 distance = math.sqrt(x...
def countLetters(testString,testChar): count = 0 for char in testString: if (char.upper() == testChar.upper()): count = count + 1 return count name1 = raw_input("What is the name? ") while(name1 <> "STOP"): print name1 c = countLetters(name1,"E") print 'The count of ...
def countdown(): n = 10 #countdown code while (n > 0): print(n) n = n - 1 print("Blastoff!") countdown() countdown()
name1 = raw_input("What is the name? ") name2 = "George" #"GEORGE" if (name1 == name2): print "Correct!" elif (name1.upper() == name2.upper()): print "You typed the same name, but didn't capitalize!" else: print "Wrong" print "done"
name1 = raw_input("What is the name? ") while(name1 <> "STOP"): print name1 count = 0 for char in name1: if ((char == "E") or (char == "e")): count = count + 1 print count name1 = raw_input("What is the name? ")
def factorial(n,s): #setup variable for running product before loop. runningProduct = 1 #compute the factorial while (n > (s-1)): runningProduct = runningProduct * n n = n - 1 return runningProduct n = 11 x = 1 factorialvalue = factorial(n,x) report = "The product of ...
name = "George Thomas Raber" names = name.split(" ") print names print type(names) for n in names: #print n.upper() for letter in n: print letter
x = 40 y = 20 def whichisbigger(x,y): if (x > y): print "x is bigger" return x elif (x == y): print "they are equal" print "Isn't that awesome" if (x == 7): print "And they are both sevens!" return x else: print "y is bigger" retur...
a = 2 b = 2 if a > b: print("A is bigger") elif a < b: print("B is bigger") else: print("A and B are the same")
""" What is the most interesting/funny/cool thing(s) about Python that you learned from this class or from somewhere else. You can use code or a short paragraph to illustrate it. """ I think the coolest thing that I learned from this class about python is how there are so many ways to write the same code to complete...
my_list = [] while 1: a = input() if a: my_list.append(a) else: break for i in my_list: chef = [] oppo = [] for j in range(len(i)): if j%2 == 0: chef.append(i[j]) else: oppo.append(i[j]) print(chef) print(oppo)
result = [] t = int(input()) for i in range(t): n = int(input()) valid_dict = {'cakewalk':0, 'simple':0, 'easy':0, 'easy-medium':0, 'medium':0, 'medium-hard':0, 'hard':0} for j in range(n): while 1: s...
for i in range(int(input())): s = input() one = s.count('1') zero = s.count('0') if one == 1 or zero == 1: print('Yes') else: print('No')
def palindrome(s): if s==s[::-1]: return len(s) return 1 def LP(s): S=s[0] for i in range(1,len(s)): if s[i]==s[i-1]: S+="ϱ"#adds ϱ between consecutive letters S+=s[i] f=LOP(S)#f is LOP of S c=0 for i in range(len(S)): if i+f>len(S): ...
"""CSC148 Assignment 1 - People and Elevators === CSC148 Fall 2018 === Department of Computer Science, University of Toronto === Module description === This module contains classes for the two "basic" entities in this simulation: people and elevators. We have provided basic outlines of these two classes for ...
q1_process= [] q2_process= [] q3_process= [] q1=-1 q2=-1 q3=-1 n= int (raw_input ("enter total number of processes: ")) time1= int (raw_input ("enter time slice of queue 1: ")) time2= int (raw_input ("enter time slice of queue 2: ")) for i in range(n): print "enter information for ", i+1,"th process" q1+=1 q1_proces...
kierrokset = int(input("Kuinka monta kierrosta?: "))#input tulos = int(0) #tässä vaiheessa nolla for i in range(0, kierrokset):#0-input tulos = tulos + i # kumuloituva kierrosnumroiden summa print("Kertymäksi saatiin:", tulos)
def korjaaja(): while True: while True: try: luku1 = int(input("Anna luku: ")) return luku1 except ValueError: print("Virheellinen syöte!") while True: try: luku2 = ...
# # @lc app=leetcode.cn id=22 lang=python3 # # [22] 括号生成 # # @lc code=start class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def dfs(left, right, path, ans): if left == 0 and right == 0: print (path)...
# # @lc app=leetcode.cn id=543 lang=python # # [543] 二叉树的直径 # # @lc code=start # 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 diameterOfBinaryTree(self, root): ...
# # @lc app=leetcode.cn id=590 lang=python # # [590] N叉树的后序遍历 # # @lc code=start """ # Definition for a Node. class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution(object): def postorder(self, root): """ :type...
# Get cumulative sum of a list # e.g cumulative_sum([1,2,3,4,5]) => [1,3,6,10,15] def cumulative_sum(arr): sumArr = [] for i in range(len(arr)): if i == 0: sumArr.append(arr[i]) else: sumArr.append(arr[i]+sumArr[i-1]) return sumArr print(cumulative_sum([1,2,3,4,5])...
def preencheMatriz(mat, lin, col): for l in range(lin): linhas = [] for c in range(col): linhas.append(int(input(str(c+1)+"º número da "+str(l+1)+"a linha da matriz: "))) mat.append(linhas) def mostraMatriz(mat, lin, col): print("Matriz: ") for l in r...
import turtle tela = turtle.getscreen() seta = turtle.Turtle() seta.pen(pencolor = "red", fillcolor = "yellow", pensize = 10) for i in range(6): seta.begin_fill() seta.circle(150 - i * 20) seta.end_fill()
n = int(input()) sequencia = 1 auxSeq = 1 num = float(input()) ant = num for i in range(n - 1): ant = num num = float(input()) if (num > ant): auxSeq = auxSeq + 1 else: if(auxSeq > sequencia): sequencia = auxSeq auxSeq = 1 if(auxSeq > sequencia): se...
""" The main logic of the bot. This file implements the database and bot command parsing. """ import json import os from collections import defaultdict import connexion import requests BOT_ID = os.environ.get('BOT_ID', 'TestID') DB_FILE = 'data.json' POST_URL = 'https://api.groupme.com/v3/bots/post' def defaultd...
#Detta var koden vi skrev på övningen ht-15 #En annan version finns i split_words14 s = "hej då ett ord till" def split(s): for pos in range(len(s)): if s[pos] == " ": for pos2 in range(pos+1, len(s)): if s[pos2] == " ": print(s[pos+1:pos2]) break split(" " + s + " ")
class Node: def __init__(self, value = None, next = None): self.value = value self.next = next def insert_after(new_node, insert_at): new_node.next = insert_at.next insert_at.next = new_node def remove_next(node): node.next = node.next.next def length(node): if node.next == None: return 1 else: return ...
import urllib.request as urlrequest import urllib.parse as parse import json #Sets API keys with open("data/keys.json") as keyFile: APIKeys = json.loads(keyFile.read()) TasteDiveApiKey = APIKeys['TasteDiveApiKey'] OMDbApiKey = APIKeys['OMDbApiKey'] def getTasteDiveURL (movies): ''' This function use...
# 모듈 내용 선언하기 from CakeShopInfo import Cakeshop from CakeCustomerInfo import Cakecustomer # 케이크와 고객 연동 class 생성 class cake_customer: def cake_data(): cake_d = [] with open('cakeshop.csv', 'r', encoding='utf-8') as f1: data = f1.readlines() # print(data) -> ['Cheese Cake, 2...
#三目表达式--三元表达式(条件表达式) # 如果条件为真,返回真,否则返回假 x = int(input("请输入第一个数:")) y = int(input("请输入第二个数:")) z = int(input("请输入第三个数:")) #写法1 print((x if (x>y) else y) if ((x if (x>y) else y) >z ) else z) #写法2 a = (x if (x>y) else y) print (a if (a>z) else z)
# -*- coding: utf-8 -*- """ Created on Tue Nov 14 16:26:36 2017 @author: adhingra """ # Hierarchical Clustering # import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # importing dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:,3:].values # using dendrograms ...
# -*- coding:UTF8 -*- #!/usr/bin/python #链表,节点 class Node: '''链表的构造快:节点的数据结构''' def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data ...
#-*- coding:UTF8 -*- #!/usr/bin/python class Stack(): '''栈的数据结构的实现''' def __init__(self): self.items = [] def isEmpty(self): return [] == self.items def size(self): return len(self.items) def push(self,item): self.items.append(item) def pop(self): ret...
# I need to use a list of lists to store the states of the fields, since there are 3 possible # states - if there had been only 2 it would have been possible to use the binary # representation of a long integer # Lists are faster than sets here because I am iterating over all fields often # encode open ground as 0, lu...
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ...
""" Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0. A word is a maximal substring consisting of non-space characters only. """ class Solution(object): def lengthOfLastWord(self, s): """ :type...
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ """ Given a sorted array and we need to return the length of the unique elements instead of the entire array. There is no need to delete the duplicate elements also. ...
''' 字符A-Z可以编码为0-25。"A"->"0", "B"->"1", ..., "Z"->"25" 现在输入一个数字序列,计算有多少种方式可以解码成字符A-Z组成的序列。 例如: 输入:19 输出:2 --->BJ T 输入:258 输出:2 --->CFI ZI 输入:0219 -->ACBJ AVJ ACT 输出:3 ''' def how_many_ways(): str = input("输入:") count = 1 # 起步一种 lens = len(str) for i in range(lens): if i == lens - 1: ...
# coding=utf-8 # 冒泡排序 def sort(list): # 执行轮次数 num = 0 size = len(list) for x in range(size): num += 1 for y in range(size - x - 1): if list[y] > list[y + 1]: list[y], list[y + 1] = list[y + 1], list[y] print '执行轮次数:' + str(num) # 优化冒泡排序 def optimizati...
#This version if for Github project import time import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def print_input_error(key_enter): print('Your input {} is invalid, try again\n'.format(key_enter)) return ...
# La formula para el índice de Masa Corporral es IMC = kg/m2 donde kg es el peso de la persona en kilogramos y m2 es la altura en metros al cuadrado. Realizar programa que calcula el IMC cuando se le provee el peso y altura print("Introducir el peso del individuo: ") peso = float(input()) print("Introducir la altura...
from .student import Student from .course import Course class RegisterStudent: name = '' age = '' address = '' email = '' in_two_installments = False course_detail = Course() def __init__(self): print('*' * 30) print('Thank you for Registering for the IW Academy!') ...
from pathlib import Path def read_text(filename): result = '' with open(filename, encoding='utf-8') as file: for line in file: result += line + '\n' return result def write_text(filename, text): with open(filename, mode='w', encoding='utf-8') as file: file.write(text) d...
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt # standard short name import random plt.ion() # sets “interactive on”: figures redrawn when updated def picks(): a = [] # make an empty list # Why all the brackets below? # a += [ brackets here to add an iterable onto a list ] ...
#Example 1: Variables (Highlight the section below and press alt-4 to uncomment) ##name = "Oswald" #This variable is a string, or normal text ##number_of_cats = 12 #This variable is an integer ##cat_food = ["fish", "kibbles", "biscuits", "cauliflower"] #This variable is a list of other values ## ##...
nome_completo = input('Digite seu nome completo: ') print('TODAS AS LETRAS MAIÚSCULAS: {}'.format(nome_completo.upper())) print() print('TODAS AS LETRAS MINÚSCULAS: {}'.format(nome_completo.lower())) print() dividir_nome = nome_completo.split() juntar_nome = ''.join(dividir_nome) print('QUANTIDADE DE LETRAS: {}'.for...
nome_completo = str(input('Digite seu nome completo: ')).strip() if 'Silva' in nome_completo: print('Foi encontrado o sobrenome SILVA no seu nome') else: print('Não foi encontrado o sobrenome SILVA no seu nome')
num = int(input('Digite um número: ')) do = num * 2 tri = num * 3 rq = num ** (1/2) print(f"O dobro desse número é {do}, seu triplo é {tri} e sua raíz quadrada é {round(rq, 1)}")
from math import trunc num = float(input('Digite um número real qualquer: ')) num_quebrado = trunc(num) print(num_quebrado) # poderia usar apenas a função int() para deixar o valor inteiro # sem a necessidade de importar módulos
import sys for i in sys.argv[1:]: i = int(i) if i % 3 == 0: print('fizz', end='') if i % 5 == 0: print('buzz', end='') if i % 3 != 0 and i % 5 != 0: print(i, end='') print('')
import random import urllib.request import sys WORD_UrL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class Mouse(object)": "Make a class named Mouse that is-a object", "class Cat(object):\n\tdef __init__(self, miao)": "class cat has-a __init__(self, miao)", "class Fish(...
import re # Password Checker Class class Password_Checker: # Function checks the password is a string value def __init__(self, password): self.password = str(password) pass # Function checks that the password has lowercase values def lowercase(self, password): return any(char.i...
# indexing import numpy as np a = np.array([[1, 2, 3], [4.5, 5, 6]], int) # 뒤에 int를 붙여주었기에 4.5를 int인 4로 바꿔줌 print(a) print(a[0, 0]) print(a[0][0]) a[0, 0] = 12 print(a) a[0][0] = 5 print(a) # List와 달리 여기 2차원 배열에서는 # [0][0] == [0, 0] # 기억해라! 우리의! 붉은! 함성을! # 들어라 보아라 기억하라 # ㅋㅋㅋㅋㅋㅋㅋ새벽코딩ㅋㅋㅋㅋㅋㅋ해탈잼
# Vector은 파이썬에서 List, Tuple, dict 등 다양하게 표현할 수 있다 a = [1, 2, 10] b = (1, 2, 10) c = {'x' : 1, 'y' : 2, "z" : 10} print(a, b, c)
import numpy as np a = np.array([1, 4, 5, 8], float) print(a) print(type(a[3])) b = np.array([5, 8, 6, "9"], float) print(b) print(type(b[3])) print(b.dtype) print(b.shape) # import numpy as np # # a = np.array([1, 4, 5, 8], float) # print(a)
# scalar_vector_product # 하나의 scalar 값을 vector에 곱함, 단 입력되는 vector의 크기는 일정하지 않음 def scalar_vector_product(alpha, vector_variable): return [alpha*element for element in vector_variable] print (scalar_vector_product(5,[1,2,3])) # Expected value: [5, 10, 15] print (scalar_vector_product(3,[2,2])) # Expected value: [6...
import random # lista_numeros =[] # for elemento in range (1,11): # lista_numeros.append(random.randint(1,100)) # for i in lista_numeros: # print(i) #________________________________________ # import random # lista_numeros =[] # for elemento in range (1,11): # a=input('escribe nombre: ') # lis...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Piggy bank application """ from __future__ import print_function import shelve from datetime import datetime from datetime import date as dtdate class Tirelire(): """ Piggy bank """ def __init__(self): #: Total amount self._total = 0.0 ...
##Q2) WAP to create a table game (game no, name , no_of_players) and insert rows in it using user defined functions create_tabe() and insert_rows() ##Manasvi,Ripunjay import mysql.connector as my mydb=my.connect(host='localhost',user='root',passwd='',database='xaviers') mycursor=mydb.cursor() def create_table() : ...
def display(): sfile= open("story.txt",'r') a = sfile.readlines() print(a) print('no of lines in a is',len(a)) now=0 for i in range(len(a)): b=len(a[i]) now=now+b print('no of character is',now-len(a)) sfile.close() display()
i = 0 while i < 5: print(i) i += 1 if i == 3: break myList = [1, 2, 3, 4] for x in myList: print(x) for x in range(10): print(x + 10)
#!/usr/bin/python3 ############################################################################### # # File: makeMapFile # Authors: Henderson Hummel, Tejas Menon # # # Purpose: generate random strings that match the map format. # Description: This script simply generates random numbers that fit the # fo...
# -*- coding: utf-8 -*- """ Created on Sun Nov 27 14:09:19 2016 @author: 文龙 """ import pylab as pl import math def initial(a,e,MP): MS=2*10**(30) x0=a*(1+e) y0=0 vx0=0 vy0=2*math.pi*math.sqrt((1-e)/(a*(1+e))*(1+MP/MS)) return [x0,y0,vx0,vy0] class orbits(): """ planetary motion progr...
def main(): T = int(input()) results = {} for _ in range(T): N = int(input()) if N in results: print(results[N]) continue lowest = N highest = N while True: #print(lowest, highest) if is_prime(lowest) and is_prime(h...
# vraag naar naam naam = input('Wat is jouw naam? ') # vraag naar leeftijd leeftijd = input('Hoe oud ben jij? ') # zin uitschrijven print(f'{naam} is {leeftijd} jaar oud.')
first_value = int(input('First Number: ')) second_value = int(input('Second number: ')) sum = first_value + second_value print("Sum: " + str(sum)) #///////////////////////////// numeric_value = '7' print(numeric_value.isnumeric()) string_value = 'Bob' print(string_value.isnumeric()) #//////////////////...
print("Simple calculator!") First_number = input("First number? ") Operation = input("Operation? ") Second_number = input("Second number? ") if First_number.isnumeric() == True and Second_number.isnumeric() == True: First_number = float(First_number) Second_number = float(Second_number) i...
import unittest import newton class NewtonTestCase(unittest.TestCase): def test_zero_degree_polynomial(self): """Are zero degree (constant) polynomials handled correctly?""" # f(x) = 2 p, p_str = newton.interpolation_polynomial([(0,2)], get_string=True) self.assertEqual(p(-3.14), 2)...
#%% # starting with imports import torch #%% # here is some iteration -- lowering the number # of hidden parameters until we no longer can get the # gradiens to vanish # this is a bit of dynamic model generation, which is # a kind of meta-learning #%% # inputs and outputs, just random values -- we'll work with real...
#%% # Regression has a different output format than classification -- # it is in real values, good old floating point numbers. # This particular dataset also has real valued data points, # so we're # going to update our data loader to be more configurable column # wise how to encode values. We'll start be brining bac...
# %load q01_longest_even_word/build.py # Default imports import re from nltk.tokenize import word_tokenize sentence = 'photographs or other images, readers can start to get a sense about the topic. This scanning and skimming helps set the expectation for the reading.' data1 = 'One great way to make predictions about ...
def linearSearch(ls,ele): for i in range (0,len(ls)): if ls[i] == ele: return i break return -1 ls = input("enter a list of numbers") ls =ls.split() result = linearSearch(ls,int(input("enter element to be found"))) if ( result == -1): print("Element not found") else: print("Element is found at ...
import time as t # Shell sort algorithm def shell(l): gap = len(l) // 2 while gap > 0: print(f"Shell:Gap is {gap}") for i in range(gap): for j in range(i + gap, len(l), gap): val = l[j] pos = j while pos >= gap and l[pos - gap] > val:...
a=100 b=200 sum=a+b print('the sum of {0} and {1} is {2}'.format(a,b,sum))
import pandas as pd # Below helps view complete dataframe in pandas, hence, it helps print it too pd.set_option("display.max_rows", None, "display.max_columns", None) """ Json data is noting but a dictionary in Python. It can be read into Pandas Dataframe by pd.read_json method. """ df = pd.read_json('data.json') # ...
import pandas as pd # Below helps view complete dataframe in pandas, hence, it helps print it too pd.set_option("display.max_rows", None, "display.max_columns", None) df = pd.read_csv('data.csv') print(df.info()) """ Prints a lot of useful info about our data, like number of columns, rows, column names, non-null dat...
# # a = [1, 3, 5, 7, 0, -1, -9, -4, -5, 8] # # 用列表生成式,生成新的列表 # b = [i for i in a if i > 0] # print("大于 0 的个数:%s" % len(b)) # # c = [i for i in range(101) if i%3 == 0] # print("倍数的个数:%s" % len(c)) # m = 0 # for i in range(101): # if i % 3 == 0: # m += 1 # print("倍数的个数:%s" %m) a = "axsbsdfsdt" prin...
""" Project Euler 15: Find the number of routes from the top left corner to the bottom right corner in a rectangular grid. How many routes are there through a 20x20 grid? """ def pascalTriangle(rows): """ Print out the pascal triangle structure and the max number in each row """ for rownum in range (rows): ...
""" Project Euler 27: Find a quadratic formula that produces the maximum number of primes for consecutive values of n """ def isPrime(n): if n%2==0: return False for i in range(3, int(n**0.5)+1,2): if n%i == 0: return False return True max_num_prime = 0 max_a_b = (0,0) limit = 1000 for a in range(-limit...
from errors import ExitGame import textwrap class Console(object): def message(self, text): """ Prints a message on the screen. """ for paragraph in text.split('\n'): print ' {}'.format( '\n '.join( textwrap.wrap(paragraph, 76) ...
name = str(input('Introduce tu nombre: ')) last_name = str(input('Introduce tus apellidos: ')) age = int(input('Introduce tu edad: ')) email = str(input('Introduce tu email: ')) dic = { 'nombre': name, 'apellido': last_name, 'edad': age, 'email': email } print(f"Hola, mi nombre es: {dic['nomb...
class Person: def __init__(self, name, surname, age, height, weight): self.name = name self.surname = surname self.age = age self.height = height self.weight = weight def get_name(self): print(f'El nombre completo es: {self.name} {self.surname}') def ind...
print("BIENVENIDO A LA CALCULADORA DE SALARIOS") selection = 'Si' while selection == 'Si': name = input("Introduce tu nombre completo: ") salary_compl = float(input("Introduce tu salario: ")) salary_iva = salary_compl * 0.84 print("El salario bruto de", name, 'es de:', salary_iva) selection = in...
from PIL import Image """ 下面介绍一下计算机存储图像的原理 w 是图像宽 h 是图像高 一个图像由 w * h 个像素点组成 每个像素点由 rgba 4 个部分组成 r 红色 g 绿色 b 蓝色 a 透明度 现在的图像 rgba 分别是一个字节表示,一个字节的数值范围是 0 - 255 也就是一个像素点 4 字节,可以表示的颜色范围是 256 的 4 次方 但是很多图像是没有 a 的,所以就只有 3 字节表示一个像素 项目要求: 参考下面的链接和本文件的代码 https://baike.baidu.com/item/%E5%8E%BB%E8%89%B2 实现 grayscale 函数,让生...