text
stringlengths
37
1.41M
import random, time numberTyped = int(input('Type a number between 0 and 5: ')) print('Thinking...') time.sleep(2) numberRandom = random.randint(0, 5) if numberTyped == numberRandom: print('Congrats bro, you are right, the number typed {}, is equal like mine, {}.'.format(numberTyped, numberRandom)) else: ...
while True: try: x = int(input()) if((x>= 0 and x < 90) or (x == 360)): print('Bom Dia!!') elif(x>=90 and x < 180): print('Boa Tarde!!') elif(x>=180 and x < 270): print('Boa Noite!!') elif(x >= 270 and x < 360): print('De Madrug...
def words(word_to_count): string_content = word_to_count.split() response = {} for item in string_content: loop_counter = 0 #Only check for items not already added to the final result if item not in response: #Compare with everything in the list ...
# Day 2 # Part 1: input is a list of passports separated by blank lines # Passports contain: # byr (Birth Year) # iyr (Issue Year) # eyr (Expiration Year) # hgt (Height) # hcl (Hair Color) # ecl (Eye Color) # pid (Passport ID) # cid (Country ID) # # Count how many passports are valid, they must contain every item excep...
# Day 8 # Part 2 # counting the difference between the code length and the strings once # we convert: # " = \" # \" = \\\", # \\ = \\\\, # \xnn = \\xnn import string input = open('input.txt') count = 0 for line in input: Line = line.rstrip('\n') search = Line.find('\\') currentCount = 4 while search > ...
# Part 1, count the number of IDs containing exactly two of any letter and then separately counting those with exactly three of any letter. # Multiply those two counts together to get a rudimentary checksum # # Part 2, find two strings in input that only differ by one character, print out matching characters import nu...
# Part 1: Input is a list of instructions: # acc increases or decreases a single global value called the accumulator by the value given in the argument. # After an acc instruction, the instruction immediately below it is executed next. # jmp jumps to a new instruction relative to itself. The next instruction to execute...
# Day 2 # Given present dimensions in presents.txt in format 1x2x3 # Part 1: work out how much wrapping paper is needed # - for each present need surface area of box + smallest side area # Paer 2: work out how much ribbon is needed # - for each present need volume of box + 2*(smallest side + 2nd smallest side) presents...
# Day 16 # recieved present from Aunt Sue # have 500 Aunt Sues # present tells you some properties of the giver # have a list of things you remember about your Aunts # work out which Aunt gave gift # # properties include: # children, cats, samoyeds, pomeranians, akitas, vizslas, goldfish, trees, cars, perfumes # if a p...
#----------------------NUMBER TYPES------------------- anInt = 1 aLong = -99999999999999999 aFloat = 3.1415926535 aComplex = 1.23+4.56J print(anInt, aLong, aFloat, aComplex) del anInt # 删除已经删过的对象时,会抛NameError: name 'anInt' is not defined # del anInt #----------------------DIVISION--------------------- print(3 / 6)...
# import requests # r = requests.get('https://www.teamleada.com') # print(r.status_code) # # returns a 200 code indicating 'OK'. # """An 'OK' status indicates that we received back some meaningful HTML # from the request. Note that this does NOT mean that the HTML is valid # and well-formed. It tells us that th...
import tkinter as tk from operator import add import pygame pygame.init() sound=pygame.mixer.Sound("Button-click-sound.mp3") window=tk.Tk() window.title("My Calculator 1.0") window.geometry("600x600") text=[] frame1=tk.Frame(window) frame1.pack(side=tk.TOP) main_label=tk.Label(frame1,text="A Basic Calculator",font=...
num=int(input()) temp=num res=0 i=0 while num: r=num%10 num=num//10 res=res*10+r if res==temp: print("It Is Palindrome") else: print("It Is Not Palindrome")
fname = input("Enter file name: ") # This line is unnecessary. It seems that the file "mbox-short" removed blank lines so that the loop will not have the same problem as in the [clip](https://www.coursera.org/learn/python-data/lecture/n7ihY/worked-exercise-lists) if len(fname) < 1 : continue fh = open(fname) count = 0...
#This program uses object oriented programming to store people's information into socialite objects from socialite import Socialite #list that holds all created objects socialite_list = [] #variable that checks input for Number of Socialites stopper = 0 print("Welcome to CS 172: Socialite Homework") #asks for how many ...
#This program allows for the computation of complex number (ones that include the imaginary number i ) from complex import complex_number import sys #the first function def a(c,k): temp_output = complex_number(1,0) a="" summation_list = [] original_object = c store_object = complex_number(1,0) ...
# library used import random import simpy # listperson in your simulation global listperson listperson = list() def number_infected(): """ calculate the number of infected in listperson """ nb = 0 for item in listperson: if item.status == "sick": nb+=1 return nb class Pe...
#Luis Fernando Duran Castillo #Calcular el pago de las entradas def CalcularPago(boletosA, boletosB, boletosC): precioA = boletosA * 3250 precioB = boletosB * 1730 precioC = boletosC * 850 total= precioA + precioB + precioC return total def imprimirtotaldeboletos (boletosA, boletosB, b...
""" Project Euler - Problem Solution 002 Copyright (c) Justin McGettigan. All rights reserved. https://github.com/jwmcgettigan/project-euler-solutions """ def is_even(num): return num % 2 == 0 def new_terms(f): return [f[1], f[0] + f[1]] def sum_of_even_fibonacci_values(limit): sum, f = 0, [1, 1] while(f[0] < limi...
""" Project Euler - Problem Solution 025 Copyright (c) Justin McGettigan. All rights reserved. https://github.com/jwmcgettigan/project-euler-solutions """ def newTerms(f): return [f[1], f[0] + f[1]] def index_of_1000_digit_fibonacci_value(): # repurposed from problem 002 index, f = 1, [1, 1] while(len(str(f[0]))...
""" Project Euler - Problem Solution 029 Problem Title - Distinct powers Copyright (c) Justin McGettigan. All rights reserved. https://github.com/jwmcgettigan/project-euler-solutions """ def distinct_powers(limit): distinct_terms = set() for a in range(2, limit+1): for b in range(2, limit+1): distinct_te...
from statistics import mean num = 0 opcao = '' listaNum = [] while opcao != 'N': num = int(input('Digite um número: ')) listaNum.append(num) opcao = input('Deseja continuar? [S/N]: ').upper()[0].strip() print('Média dos listaValores lidos: {:.2f}'.format(mean(listaNum))) print('O maior valor lido foi: {}'.f...
from datetime import date cadastro = {} cadastro['nome'] = input('Nome: ').capitalize().strip() anoNasc = int(input('Ano de Nascimento: ')) cadastro['idade'] = date.today().year - anoNasc cadastro['ctps'] = int(input('Carteira de Trabalho [0 não tem]: ')) if cadastro['ctps'] != 0: cadastro['anoContr'] = int(input('...
def leiaInt(msg): """ -> Função que só aceita a leitura de números :param msg: recebe texto pedindo um número :return: retorna o resultado na análise """ num = input(msg) while num.isnumeric() is False: print('\033[31mERRO! Digite um número inteiro válido.\033[m') num = input...
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) med = (n1 + n2) / 2 print('Sua média é {:.1f}\nDe acordo com a sua média:'.format(med)) if med < 5: print('Você está \033[31mREPROVADO') elif 5 <= med <= 6.9: print('Você está em \033[33mRECUPERAÇÃO') else: print('Par...
listaPeso = [] for c in range(1, 6): peso = float(input('Peso da {}ª pessoa em Kg: '.format(c))) listaPeso.insert(c, peso) print('Maior peso: {}Kg'.format(max(listaPeso))) print('Menor peso: {}Kg'.format(min(listaPeso)))
cidade = input('Digite o produto de uma cidade: ').strip().upper() print('A cidade começa com a palavra Santo? {}'.format('SANTO' in cidade[:5]))
print('-=-'*20) print('\033[31mCONVERSOR DE BASE\033[m') print('-=-'*20) num = int(input('Digite um número inteiro: ')) print('''\033[34mBases de conversão: [ 1 ] para binário [ 2 ] para octal [ 3 ] para hexadecimal\033[m''') base = int(input('Digite o número correspondente a base selecionada: ')) if base == 1: con...
a1 = int(input('Digite o primeiro termo da PA: ')) r = int(input('Digite a razão da PA: ')) a10 = a1 + (10 - 1) * r print('[ ', end='') for c in range(a1, a10 + r, r): print('{}'.format(c), end=' ') print(']', end='')
print('\033[34mANALISE DE EMPRÉSTIMO IMOBILIÁRIO\033[m') valorCasa = float(input('Qual o valor da casa, que você deseja comprar? R$')) salario = float(input('Quanto é a sua renda? R$')) anos = int(input('Em quantos anos você deseja parcelar? ')) mensal = valorCasa / (anos * 12) print('Valor da casa: R${:.2f}\nSalário d...
nome = input('Qual o seu produto completo? ').strip().upper() print('Prazer em te conhecer {}'.format(nome)) print('Seu primeiro produto é {}'.format(nome.split()[0])) print('Seu último produto é {} \nEsta correto?'.format(nome.split()[len(nome.split()) - 1]))
num = int(input('Digite um número para ver sua tabuada: ')) print('-=-'*15) for c in range(0, 11): print('{} i {:2} = {}'.format(num, c, num*c)) print('-=-'*15)
def leiaDinheiro(msg): """ -> Função que verifica se um preço digitado é valido :param msg: recebe a menssagem pedindo um preço :return: retorna o preço válido """ while True: preco = input(msg).strip().replace(',', '.') if preco.isalpha() or preco == "": print(f'\033...
import sys class BalancedTreeNode(object): def __init__(self, parent, key, value): self.key = key self.value = value self.parent = parent self.left = None self.right = None def find(self, k): if k == self.key: return self elif k < self.key: ...
class TreeNode(): def __init__(self, key=None, value=None): self.key = key self.value = value self.left = None self.right = None self.parent = None def init_node(self, left, right): self.left = left self.right = right class BinaryTree(): def __init_...
import random def who_won(player1, player2): print("Jugador = ", player1, ", Computador = ", player2) if player1 == "Piedra" and player2 == "Tijeras": return "player1" elif player1 == "Papel" and player2 == "Piedra": return "player1" elif player1 == "Tijeras" and player2 == "Papel": ...
class Dog: def __init__(self, name, age, furcolor): self.name = name self.age = age self.furcolor=furcolor def bark(self , str): print("BARK! " + str ) mydog = Dog("John", 20, "Brown") mydog.bark("Here is Food!") print(mydog.age)
class Queue: QUEUE_SIZE = 10 def __init__(self): self.queue = [None for i in range(Queue.QUEUE_SIZE)] self.front = 0 self.rear = 0 def en_queue(self, data): if (self.rear == Queue.QUEUE_SIZE-1 and self.front == 0) or (self.rear == self.front-1): raise Exception...
#!/usr/bin/python # coding=utf-8 # # Author: Kristian Botnen <kristian.botnen@uib.no> # # # This script downloads a vagrantbox and a checksumfile. # # After download it calculates the checksum of the downloaded vagrantbox and checks if it matches the one given from # in the sha256sum text file. # # If it matches, the v...
class student: ID = "" CGPA = "" def set_value(self,ID,CGPA): self.ID = ID self.CGPA = CGPA def Display(self): print(f"ID :{self.ID},CGPA : {self.CGPA}") sakil = student() print(isinstance(sakil,student)) sakil.set_value(101,3.80) sakil.Display()
# Time complexity : O(log n to the base 2s) def main(): # array takes in space separated numbers from the user array = list( map(int, input("Enter the numbers separated with space: ").strip().split(" "))) # search takes in the number ot be searched for search = int(input("Enter the element y...
from math import pi #invoer r= int(input('de afstand tussen de satelliet en het middelpunt van de aarde: ')) v= int(input('de snelheid van de satelliet ten opzichte van de aarde: ')) #berekening a= ( pow(r*10, -9) ) / 2 * pow(10, -9) - r*v**2 p= 2 * pi * pow(pow(a, 3)/pow(10, -9), 0.5) print(a) print(p) #ui...
#invoer n_X= float(input('aantal deeltjes S: ')) #berekening N_A= 6.020*10**23 N_X= n_X*N_A m_X= 32.06*n_X #uitvoer print(m_X) print(N_X)
def roteer(woord, n): geroteerd_woord = '' for letter in woord: x = woord.find(letter) + n if x >= len(woord)-1: while x >= len(woord)-1: x -= len(woord) else: pass geroteerd_woord += woord[x] return geroteerd_woord print(roteer('as...
# -*- coding: utf-8 -*- # # Python version: 2.6.6 # Developer by: @itrogeno # Date: 24-05-2011 # Description: Implementacion de un Arbol Binario en Python. class Tree(): '''Arbol Binario''' left = None right = None data = [] def __init__(self, value): self.value = value def app...
from itertools import cycle from functools import partial res = {} def move_right(pos): return pos[0] + 1, pos[1] def move_down(pos): return pos[0], pos[1] - 1 def move_left(pos): return pos[0] - 1, pos[1] def move_up(pos): return pos[0], pos[1] + 1 def bottom_right(pos): return pos[0] + ...
''' Created on Nov 30, 2017 I pledge my honor that I have abided by the Stevens Honor System. ytakezaw THE CONNECT FOUR GAME LAST HW!!! @author: Yoshika Takezawa ''' import sys class Board(object): '''three data members: there will be a two-dimensional list (a list of lists) containing characters to represe...
# --coding: utf-8 -- # Python knows you want something to be a string when you put either # " (double-quotes) or ' (single- quotes) around the text # Creating a string and also using string formating to induce a digit in that string x = "There are %d types of people." % 10 # Creating a string variable named "binary" b...
import datetime class BikeRental: def __init__(self,stock=0): """ Our constructor class that instantiates bike rental shop. """ self.stock = stock class Customer: def __init__(self): """ Our constructor method which instantiates various customer objects. ...
#!/usr/bin/env python # # blackjack.py # # Exercise 5.1: Blackjack import numpy as np import random class Env: def __init__(self): self.deck = [1,2,3,4,5,6,7,8,9,10,10,10,10] def first_two_cards(self, player, dealer): """ Returns: state = (player's su...
"""the classic knapsack algorithm using dynamic programming INPUT: a list of tuples where each tuple has 2 elements (value, weight) OUTPUT: with 2 values -> (max_value, selected_items) NOTE: if there are multiple combination of possible items the algorithm will only return one of them """ ...
import random words = ['python', 'java', 'kotlin', 'javascript'] count = 0 random_word = list(random.choice(words)) progress = list('-' * len(random_word)) print('H A N G M A N') while count < 8: print(f'\n{"".join(progress)}') attempt = input('Input a letter: ') if attempt in set(random_word): f...
#!/usr/bin/python3 """ Week 2 Search Engines / Zoekmachines @author Leon F.A. Wetzel University of Groningen / Rijksuniversiteit Groningen l.f.a.wetzel@student.rug.nl """ import sys import pickle import re tweets = pickle.load(open('tweets.pickle', 'rb')) def main(): """ Write a Python3 program which read...
#!/usr/bin/python3 """ Week 2 Search Engines / Zoekmachines @author Leon F.A. Wetzel University of Groningen / Rijksuniversiteit Groningen l.f.a.wetzel@student.rug.nl """ import sys import pickle # load pickles db = pickle.load(open('db.pickle', 'rb')) tweets = pickle.load(open('tweets.pickle', 'rb'), encoding="utf-...
class Location: locations = [] def __init__(self, province, county, commune, commune_type, name, typ): self.province = province self.county = county self.commune = commune self.commune_type = commune_type self.name = name self.typ = typ @staticmethod def...
# 2 - Write a function in python that will take a list of numbers n as input and return # the largest 2 elements in the list. Don't use the sort method. n = [10, 20, 90, 50, 80] def largestElement(n): first_largest = max(n[0], n[1]) second_largest = min(n[0], n[1]) for i in range(2 ,l...
from abstract_tile import AbstractTile import constants as ct class Tile(AbstractTile): """ Represents a tile in the game onto which fish or players rest. """ def __init__(self, fish_no: int): super().__init__() # Validate params if not isinstance(fish_no, int) or fish_no < ct...
import sys sys.path.append('../Common') from state import State from exceptions.OutOfTilesException import OutOfTilesException from action import Action from position import Position from constants import VERY_LARGE_NUMBER from game_tree import GameTree from color import Color class Strategy(object): """ P...
import time import kivy class TaskTracker(): def __init__(self, location_info): self.location_info = location_info self.list_of_tasks = {} def check_time(self): """ Returns the time at the user's location. """ print("The time now is " + str(time.localtime()) + ".") def timer(self, minutes): """ Ru...
# print strings with quotes print("hello world") print('hello world') # print multiline strings with triple quotes print('''hello world''') print("""hello world""") print(''' Hello My name is Todd ''') # escape character '\' print('I\'m a human') # concatenate print('statement 1 ' + 'statement 2') # convert other '...
from third import count_letter_in_string import unittest class TestGreeter(unittest.TestCase): def setUp(self): self.stringempty = '' self.notastring = 345 self.stringwith_four_a = 'hello alabama' def test_emptystring(self): self.assertEqual(count_letter_in_string(self.stringe...
import time import temple1 import importantStuff characterInventory = importantStuff.characterInventory stick = importantStuff.stick mName = importantStuff.mName runOrFight = importantStuff.runOrFight # def add_inventory(key, amount): def play_again(): play = input("Do you want to play again?" "...
import abc from typing import Any, Callable, NamedTuple class INode(metaclass=abc.ABCMeta): """Tree node interface.""" @abc.abstractmethod def decide(self, variables: NamedTuple) -> Any: pass class Leaf(INode): """Leaf for a tree.""" def __init__(self, value: Any) -> None: self...
#!/usr/bin/python import sys ''' 0: eat 0 cookies 1 time 1: eat 1 cookie 1 time 2: eat 1 cookie 1 time, eat 1 cookie 1 time 2: eat 2 cookies 3: eat 1 cookie 1 time, eat 1 cookie 1 time, eat 1 cookie 1 time, eat 2 cookies 1 time, eat 1 cookie 1 time 3: eat 1 cookie 1 cookie 1 time, eat 2 cookies 1 time 3: eat 3...
import cmd import textwrap import sys import os import time import random from pygame import mixer from items import * from map import * screen_width = 80 helpMenu = False musicOn = False titleMenu = True sys.screen_width = screen_width #### player Setup #### class player: def __init__(self): self.name = '' self.h...
# Circles and Squares # Raster and Vector from abc import abstractmethod, ABC class Renderer(ABC): @abstractmethod def render_circle(self): pass class VectorRenderer(Renderer): def render_circle(self, radius): return f'Drawing on the screen for circle with radius {radius}' class Raster...
class Buffer: def __init__(self, height, width): self.height = height self.width = width self.buffer = [''] * (self.height * self.width) def write(self, text): self.buffer.append(text) def __getitem__(self, item): return self.buffer[item] class ViewPort: def _...
def dup_array(a): l=len(a) for i in range(l): a.append(a[i]) print(a) a=[1,2,3] dup_array(a)
import math import os import random import re import sys # # Complete the 'isBalanced' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def isBalanced(s): brackets={')':'(',']':'[','}':'{'} l=0 r=len(s)-1 b=set("[]{}()") while l < ...
def rotate_array(a,n): ''' Algo: - calculate the number of rotations to be done in case n is greater than length: n = n%l note: 5%6 is 5 , 5/6 is .833 and 5//6 is 0 if n is negative then number of rotation in right becomes n = n + l ''' l=len(a) t=a[l-n:] print(l...
def powerset(s,i,cur): if i == len(s): print(cur) return powerset(s,i+1,cur+s[i]) powerset(s,i+1,cur) def powerset_using_stack(a): ''' number of element in powerset = 2^n algo: 1. start with empty subset array. 2. Now for each element in the array, add it to each...
def lca1(root,n1,n2, v): if root == None: return None if root.val==n1: v[0] = True return root if root.val == n2: v[1] = True return root root_left = lca1(root.left, n1,n2,v) root_right = lca1(root.right, n1, n2,v) if (root_left and root_right): return root if root_left: return root_left elif ro...
import math class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None def height(root): if not root: return 0 return max(height(root.left), height(root.right))+1 def is_balanced(root): if not root: return True lh = height(root.left) rh = height(root.right) ...
class Solution: # @param A : root node of tree # @return a list of list of integers def solve(self, root): def path(root): if not root: return [] stack = [] return (all_path(root, str(root.val), [])) def all_path(r...
import math from collections import defaultdict def bfs(source, graph, n): q = [] visited = [False]*(n+1) visited[source] = True q.append(source) while q: vertex = q.pop(0) print(vertex, end = " ") for neighbours in graph[vertex]: if visited[neighbours] == False: q.append(neighbours) visited[nei...
#Bliblioteca Turtle from turtle import* #Fornece Funcoes matematicas from math import* #Variaveis r = 200 inc = 2*pi/100 t=0;n = 1.5 #loop for i in range(100): x1 = r*sin(t);y1 = r*cos(t) x2 = r*sin(t+n);y2 = r*cos(t+n) penup();goto(x1,y1) pendown();goto(x2,y2) t+=inc
from tkinter import* from tkinter import messagebox class EntryDemo(Frame): def __init__(self): Frame.__init__(self) self.pack(expand = YES, fill = BOTH) self.master.title("Meu Retangulo area Calculada") self.master.geometry('200x100') self.configure(background...
# Daily Coding 40 # Given an array of integers where every integer occurs three times except for one integer, which # only occurs once, find and return the non-duplicated integer. # For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19. # Do this in O(N) time and O(1) space. def non_dup...
# Daily Coding 7 # This problem was asked by Facebook. # Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it # can be decoded. # For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. # You can assume that the messages are decodable. ...
# Daily Coding 41 # Given an unordered list of flights taken by someone, each represented as (origin, destination) # pairs, and a starting airport, compute the person's itinerary. If no such itinerary exists, return # null. If there are multiple possible itineraries, return the lexicographically smallest one. All # fli...
# Daily Coding 12 # There's a staircase with N steps, and you can climb 1 or 2 steps at a time. Given N, write a function # that returns the number of unique ways you can climb the staircase. The order of the steps matters. def number_of_unique_ways(n, list): cache = [0 for _ in range(n + 1)] cache[0] = 1 ...
# Daily Coding 27 # Given a string of round, curly, and square open and closing brackets, return whether the brackets are # balanced (well-formed). # For example, given the string "([])[]({})", you should return true. # Given the string "([)]" or "((()", you should return false. def is_balanced(brackets): valid_br...
# Simple Data Parser for Data in Files # I created this to read a text file and grab specific data I want from each line # In particular each line of data contains a bunch of text, and the data I want is enclosed in Parentheses # Assumes that each line is properly formatted (no safety checks) # Imports import os # Ge...
#!/usr/bin/python # # first : Search a hard-coded string # Author: T. Palmer # # Initial Release: January 2018 Version 1.0.0 def main(): testString = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" # Capture command-line user input using raw_input searchWord = raw_input("Please enter search term: ") ...
import pygame import numpy as np import random pygame.init() win_len=500 win_bre=600 inc=500//9 class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def print(self): if s...
# #1:join方法: # from time import ctime,sleep # import threading # def music(func): # for i in range(2): # print("I was listening to %s. %s" % (func,ctime())) # sleep(1) # print("end listening %s" % ctime() ) # # def move(func): # for i in range(2): # print("I was at the %s ! %s" ...
import time #1:使用help函数用于查看相应的帮助文档 # print(help(time)) #2:获取时间戳:time.time() ====***** # print(time.time()) #3:计算cpu执行的时间:time.clock() # time.sleep(3)#cpu在这3秒的时间内没有工作。 # print(time.clock()) #4:cpu休息time.sleep(3):====****,这个经常被用到。 #5:gmtime():结构化时间 和我们国加的北京时间差8个小时。 # print(time.gmtime())#time.struct_time(tm_year=20...
# class Foo: # def __init__(self,name,age): # self.name = name # self.age = age # def show(self): # print(self.name,":",self.age) # # obj = Foo()#obj对象,也是Foo类的实例(实例化) # # #这里创建了三个Foo类的实例。 # # obj1 = Foo() # # obj2 = Foo() # # obj3 = Foo() # # #单例目的:就是永远使用同一份对象。 # #1:单例模式简介: # v = None # ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by fengL on 2017/9/16 #1:多进程的基本使用:创建多进程 # from multiprocessing import Process # import time # def f(name): # time.sleep(1) # print('hello', name,time.ctime()) # # #在Windows下面启动子进程需要添加如下的语句。 # if __name__ == '__main__': # p_list=[] # #这里创建了三个子进程。 #...
#中国的所有省份,用面向对象? #1:类中的字段。 # class Province: # #静态字段:属于类 # country = "中国" # def __init__(self,name): # #普通字段:属于对象 # self.name = name # # henan = Province('河南') # hebei = Province('河北') # #普通字段:只能通过对象来访问。 # print(hebei.name) # # #静态字段:可以直接通过类名访问。 # print(Province.country) # # #静态字段也可以通过,对象访问 #...
import socketserver,socket #1:创建socket对象;使用默认参数创建socket对象。 sk = socket.socket() print(sk) #2:绑定ip和端口 address = ("127.0.0.1",8088) sk.bind(address)#参数必须是元组 #3:让服务器监听端口,等待客户端链接。 sk.listen(3)#参数3指定允许排队的个数 #4:接受客户端链接 print("waiting for client.......") conn,addr = sk.accept()#接受client端请求;conn,是客户端的socket对象。 # # print(conn)...
#1:字符串的基本操作: # print("你好Python")#python3默认的编码为Unicode,所以默认是支持中文的。 #2:字符-和字符编码 # print(ord('A'))#获取字符的整数表示 # print(chr(66))#编码转换为对应的字符 #3:字符串和字节互换 print('ABC'.encode('ascii'))#以Unicode表示的str通过encode()方法可以编码为指定的bytes(b'ABC') print(b'ABC'.decode('ascii'))#如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法: #...
a = 1 b = "2" # File "21-runtime-errors.py", line 8 #     print(a + b) #         ^ # SyntaxError: invalid syntax # print(int(2.5) # print(int(2.5)) # correct # Traceback (most recent call last): #   File "21-runtime-errors.py", line 14, in <module> #     print(a + b) # TypeError: unsupported operand type(s) for +: 'in...
def divide(number,by): try: return number/by except ZeroDivisionError: print("Zerro division is meaningless") # print and continue print(divide(10,0))
#3. Escribe un programa en Python que acepte una cadena de caracteres y cuente el tamaño de la cadena y cuántas veces aparece la letra A (mayúscula y minúscula) miString = input("Introducir String: ") longitud = len(miString) A = miString.count("A") a = miString.count("a") print ("El tamaño del String es: ", longi...
from HillClimbing import HillClimbing from RandomRestartHC import RandomRestartHC from SimulatedAnnealing import SimulatedAnnealing from Genetic import Genetic import numpy as np # TODO - Comment Code # Performance Improvements # TODO - Tournament Selection # TODO - from random import randint n = int(input("What is ...
asdf = { 'nombre': 'emerson', 'edad': 30, 'dni': 70288113 } # for key in asdf: # print(asdf[key]) # for value in asdf.values(): # print(value) for key, value in asdf.items(): print(f'{key}: {value}') print(asdf.keys()) print(asdf.values())
# def unt(nombre, edad, procedencia='Trujillo'): # print(f'Hola soy {nombre}, tengo {edad}, vivo en {procedencia} y soy un estudiante de la UNT') # unt(edad=20, nombre='Nelson') # //=============================== # def estudiantes(*args): # print(type(args)) # estudiantes(54, 'adsf', True, 5.78, 'Hola') # ...
# TO-DO: Complete the selection_sort() function below def selection_sort(arr): # loop through n-1 elements for i in range(0, len(arr)): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(i+1, len(arr)): ...
import matplotlib.pyplot as plt import os.path import os.path directory = os.path.dirname(os.path.abspath(__file__)) #Open the file filename = os.path.join(directory, 'touchdowns.csv') datafile = open(filename,'r') data = datafile.readlines() #Creates empty list for weight values and touchdowns scored value...