text
stringlengths
37
1.41M
# Tomas Brazas - G00349242 # Graph Theory 2019 Assignment # -- Application Description/Tasks -- # 1)"Parse the regular expression from infix to postfix notation." # 2)"Build a series of small NFA's for parts of the regular expression." # 3)"Use the smaller NFA's to create the overall NFA." # 4)"Implement the matching a...
class GraphNode(object): def __init__(self, w): self.label = w self.neighbors = [] class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: Set[str] :rtype: int """ ...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): ret = '[' + str(self.val) + ',' t = self.next while t != None: ret = ret + str(t.val) + ',' t = t.next ret ...
#!/usr/bin/env python def possible_next_states(s): ret = [] for i in range(len(s) - 1): if s[i] == '+' and s[i+1] == '+': ret.append(s[:i] + '--' + s[i+2:]) return ret def first_player_winnable(s): pstate = possible_next_states(s) if len(pstate) == 0: return False ...
import math class Solution(object): def constructRectangle(self, area): """ :type area: int :rtype: List[int] """ if area < 1: return [0, 0] def abs(x): if x[0] > x[1]: return x[0] - x[1] return x[1] - x[0] ...
#!/usr/bin/env python # coding: utf-8 # # Write a program to convert fahrenheit to kelvin and celsius both? # In[20]: print("Convert 68 degrees Fahrenheit to degrees Celsius") temperature = 68 T = (temperature-32)*5/9 print(T) # In[21]: print("Convert 60 degrees Fahrenheit to degrees Kelvin:") temperature1 = 6...
#!/usr/bin/env PYTHON #Will count the given entries in a csv file if you know the item #and column name you're searching import os, csv, re def main(): myPath = input("Gimme a csv to parse: ") with open(myPath, 'r') as myFile: myFileReader = csv.reader(myFile) userItem = input("Enter an ...
from pygame.sprite import Sprite class Explosion(Sprite): """A class to represent an explosion sprite.""" def __init__(self, screen, sprite_sheet, rect): """Initialize the explosion at the alien location.""" super(Explosion, self).__init__() self.screen = screen self.rect = re...
# this file generate new guess game. # from first_project.Live import load_game import random # function to generate a random number for the user to guess def generate_number(difficulty): return random.randint(1, difficulty) # this function get the guessed number that the user prompted def get_guess_from_user(dif...
import numpy import math import itertools import copy class System: def __init__(self, modulus, area, nodes, fixedNodes, connectivity, forces): """ :param modulus: Modulus of the elements :param area: Area of the elements :param nodes: List of the nodes in the system :param...
#!/usr/bin/env python # -*- coding: utf-8 -*- #:1+x+x2+x3 +...+xn def progresion (x,n): """Función que devuelve la suma de una progresion dado un rango""" suma=1 for exp in range(1,n+1): suma=suma+(x**exp) return suma x = progresion(6,3) print(x)
mes = int(input("Escribe el mes ")) diacomienzomes = input("Dia en el que comienza el mes: L, M...") dias = 0 contador=0 if mes == 1: mes = 'Enero' numdias = 31 elif mes == 2: mes = 'Febrero' numdias=28 elif mes == 3: mes = 'Marzo' numdias = 31 elif mes == 4: mes = 'Abril' numdias = 31 ...
#!/usr/bin/env python # -*- coding: UTF-8 -*-. contador=0 numeros=0 suma=0 while contador < 50: contador+=1 numeros+=2 suma+=numeros print(numeros,end=", ") print() print("La suma de todos es " + str(suma)) #igual que el otro
#!/usr/bin/env python # -*- coding: utf-8 -*- import lee_csv def dicacsv(fichero,lista): """Recibe un fichero y una lista de diccionarios que fue creada a partir de un CSV en dicho fichero se escribirán los datos de todos los diccionarios""" with open(fichero,'w') as fman: # con la primer...
#!/usr/bin/python3 #Programa que opera los numeros segun la opcion que elijas con control de errores try: opciones = int(input("¿Qué quieres hacer? \n Opción 1: Sumar \n Opción 2: Restar \n Opcion 3: Multiplicar \n Opcion 4: Dividir\n" )) if opciones <= 4: num1=int(input("Introduce un número: ")) num2=int(in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from mazo import Mazo from carta import Carta import random class PuntosMayor: """Juego donde gana la carta mayor, en la partida se reparten tantas cartas como jugadores haya, se miran los valores y gana el más alto""" def __init__(self, jugadores=[]): ...
#!/usr/bin/env python # -*- coding: UTF-8 -*-. listanumero=[] principio=0 while principio in range(0,52): principio+=1 listanumero.append(principio) for numeros in listanumero: if numeros%2!=0 and numeros!=principio: numeros+=2 if numeros%2==0: numeros=52-numeros print(numeros,end=", ") #no sé si esto ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- #Solicitar por teclado una cantidad de dinero con decimales hasta los céntimos y calcular el cambio en dinerototal y monedas de curso legal. dinerototal = float(input(" Dinero a cambiar: ")) listadeeuros = [500,200,100,50,20,10,5,2,1,0.50,0.20,0.10,0.05,0.02,0.01] for v...
# area of circle import math radius = float(input("Enter radius of the circle:")) area = ((math.pi) * (radius ** 2)) print("The area of the circle with radius {} is: {}".format(radius, area))
# 5 guys, one monkey, pile of coconuts # one by one a guy takes 1/5 of the (remaining) pile, but since the pile # is not divisible by 5 gives one coconut to monkey. # After this the remaining pile is divided to five parts (giving one coconut to monkey) # monkey has now 6 coconuts, how many there were originally ? pil...
#Autor: Martha Margarita Dorantes Cordero #porcentajes m = int(input("Mujeres inscritas: ")) h = int(input("Hombres inscritos: ")) t = m+h; print('Total de inscritos: ',t) print('Porcentaje de mujeres: {0:.1f}%'.format(m/t*100)) print('Porcentaje de hombres: {0:.1f}%'.format(h/t*100))
import random def initMatrix(n) : randomInts = range(1, n*n+1) # generate random number random.shuffle(randomInts) # shufflel random numbers # task: create a n by n matrix and fill it with the random numbers mat = [] for i in range(n) : # 1 line code mat.append([]) for j in range(n) : # 1 line code ...
import bingo_mod def main(): mat = bingo_mod.initMatrix(8) bingo_mod.printMatrix(mat) bingo_numbers=[] while True: number=input('Input bingo number: ') try: number=int(number) # check if integer bingo_mod.updateMatrix(mat, number) # update bingo matrix bingo_mod.printMatrix(mat) # print matrix bi...
import time class Chrono: def __init__(self, class_name=""): self.class_name = class_name self.start_time = None self.delay_s = None def start(self): #self.start_time = time.clock() self.start_time = time.perf_counter() return self def stop(self, function_...
# how to use arguments(which is same as parameters) and keyword arguments # you can use *(asterisk) when you do not know how many args and kwargs would be used in function def myfunction(*args, **kwargs): return args, kwargs if __name__ == '__main__': mylist = [1,2,3] argument1 = 3.14 argument2 = True...
# our alphabet starts at g_start = ord('a') # and it ends at g_end = ord('z') # so that we have end - start letters in between, + 1 g_size = g_end - g_start + 1 # shifts letters by i places (with wrap) # TODO: add support for uppercase def shift(c, i): return chr((ord(c) - g_start + i) % g_size + g_start) def get...
from abc import ABC, abstractmethod from cmath import sin import numpy as np # Скорость движения;V;C # Высота;H;C # Плотность;Ro;C # Давление на составную часть 1;P1;F # Давление на составную часть 2;P2;F # Давление на составную часть 4;P4;F class Functions(ABC): type_of_funcs = 0 @abstractmethod def cre...
from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow import sys ## "self" is like "this" in Java ## we are extending QMainWindow class MyWindow(QMainWindow): def __init__(self): ## calling the constructor of QMainWindow super(MyWindow, self).__init__() self.setGeometry(200, 200, ...
name = '' while name != 'Solomon Asiedu': print('Type your name') name = input() print('You have now typed your name, Thank you '+name)
import bs4, requests, pyperclip def getWebsiteSubHeadings(websiteUrl = pyperclip.paste()): res = requests.get(websiteUrl) listHeaders = [] if res.raise_for_status() == None: soup = bs4.BeautifulSoup(res.text, 'html.parser') elems = soup.select('html body div.main div h2') for i in...
import random class Car: numOfCars = 0 __speed = 0 numOfSeats = 0 def __init__(self, model, year, horsepower): self.model = model self.year = year self.horsepower = horsepower Car.numOfSeats = 4 Car.numOfCars += 1 Car.__speed = random.randint(300, 500) ...
def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 else: print(number * 3 + 1) return number * 3 + 1 try: userNumber = int(input('Enter a number: ')) while userNumber != 1: userNumber = collatz(userNumber) collatz(userNumber...
# Guessing Game Challenge #Author: Faisal Hossain # Let's use `while` loops to create a guessing game. # The Challenge: # # Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are: # 1. If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS"...
class Guess: def __init__(self, word): self.secretWord = word self.guessedChars = set() self.numTries = 0 self.wordList = ["_" for i in range(len(word))] self.currentStatus = "".join(self.wordList) def display(self): print("Current:", self.currentStatus) ...
def factorial(num): res = 1 while num > 1: res *= num num -= 1 return res while True: try: number = int(input("Enter a number: ")) except ValueError: print("Please enter only a integer !!") else: if number == -1: break elif number == ...
def factorial(numStr): r = 1 while numStr > 1: r *= numStr numStr -= 1 return r def decToBin(numStr): r = bin(numStr) return r def binToDec(numStr): r = int(numStr, 2) return r def decToRoman(numStr): r = numStr return r
#========= ONLY RUN THIS FILE IF YOU WANT TO CREATE AN EMPTY DATABASE. ========# import sqlite3 DB_FILE = "../database.db" def init_db(): db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() #Create accounts table (empty) c.execute( """ CREATE TABLE IF ...
import random import sys import re class Esercizio1: def __init__(self, argv): try: self._path = argv[0] except: self._path = 'words.txt' def get_word(self): words = open(self._path, 'r').readlines() while True: word = (random.choice(words))...
def count(line): """ インデント数取得 """ return len(line) - len(line.lstrip()) def get_next_block(lines): """ 次のブロック取得 """ # 空行開始の場合は非空行で終了 if lines[0].strip() == '': return get_not_empty_line(lines) target_indent = count(lines[0]) changed = False for i, line in enumerate(lines[1:]...
#!/usr/bin/env python s = input() abc = 'abcdefghijklmnopqrstuvwxyz' for c in abc: print(s.find(c), end=' ') print()
#!/usr/bin/env python s = input() abc = "abcdefghijklmnopqrstuvwxyz" cnt = [[c, 0] for c in abc] for i, c in enumerate(abc): cnt[i][-1] += s.lower().count(c) cnt2 = sorted(cnt, key=lambda x: x[-1], reverse=True) if (cnt2[0][-1] == cnt2[1][-1]): print('?') else: print(cnt2[0][0].upper())
#!/usr/bin/env python n = int(input()) cnt = 1 stop = False for i in range(1,n+1): for k in range(1,i+1): if cnt == n: if i%2 == 0: print("{}/{}".format(k, i-k+1)) else print("{}/{}".format(i-k+1, k)) stop = True break ...
#!/usr/bin/env python n = int(input()) s = input() nums = [int(c) for c in s] print(sum(nums))
from math import * print(' /|') print(' / |') print(' / |') print('/___|') name = "Budi" age = 17 phrase = 'Saya ' + name + '\nSaya berusia ' + str(age) + ' tahun' print(phrase) print(len(phrase)) my_num = 2 print(pow(my_num, 2)) print(sqrt(36))
""" Print 1 to 100 in rows of 10 """ for i in range(1, 11): for j in range(1, 11): print(i * j, end ="") print("") print("End of the program")
""" Assert statement is used to check a condition and throws AssertionError """ x = int(input("Enter a number:")) print(x) assert (x>0), "Wrong Number Entered" print("Entered number is ", x)
str1 = "Strings functions used in this program" str2 = "string to compare" print(str1) print("length of the string {}".format(len(str1))) print("Compare the strings ") print(str1 is str2) print(str2 == str1) print(str2 in str1) print("reverse the string") print(str1[::-1]) print("Concatenate str1 and str2: ", str1 +...
"""Using the bit wise operators a sample program """ def getRGBfromInt(in_rgbinterger): blue = in_rgbinterger & 255 green = (in_rgbinterger >> 8) & 255 red = (in_rgbinterger >> 16) & 255 return [red, green, blue] def getIntFromRgb(in_rgb): red = in_rgb[0] green = in_rgb[1] blue = in_rgb[2...
""" Display the right angle of 11 rows """ for i in range(1, 11): for j in range(1, i+1): print("* ", end="") print() print("End of the program")
""" Creating List accessing elements in list common operators slicing + and * operators in lsit in and not in operator traversing list using loop list method list comprehension """ """ Creating the lists """ l1 = list() l1 = [1, 3, 4, 5, 6] l2 = ["this", "is", "string", 12] l3 =list("python") print(l3) print(l3[1]) p...
from abc import ABC, abstractmethod class Shape(ABC): def __init__(self, pos, color=None): self.x = pos[0] self.y = pos[1] @abstractmethod def to_poly(self): pass class CornerRect(Shape): def __init__(self, pos, width, height): super().__init__(pos) self.wi...
from FlaUILibrary.flaui.exception import FlaUiError class TreeItemsParser: """ Helper class which handles the management of the given location string. The location is used to locate the exact tree item in the tree control. Examples: location = N:Nameofitem1->N:Nameofitem2->N:Nameofitem3 location =...
def triangle(n1, n2, n3): ''' a program in Python to classify triangles''' n1 = int(n1) n2 = int(n2) n3 = int(n3) res = " " if n1 == 0 or n2 == 0 or n3 == 0: res = "Invalid Input" elif n1 == n2 == n3: res = "equilateral" elif n1 == n2 or n1 == n3 or n2 == n3: res...
import pandas as pd import os import sys from sklearn.preprocessing import MinMaxScaler def get_csv_data(filename, index=0): ''' Gets data from a csv file and puts it into a pandas dataframe ''' if os.path.exists(filename): print( filename + " found ") data_frame = pd.read_csv(filename...
import pandas as pd from candidateaffiliation import Candidatesimilarity Candidate=Candidatesimilarity() df=pd.read_csv("../Processed Election Data/voterdata2012_updated.csv") statelist=df["State"].drop_duplicates() states=statelist.as_matrix() stateswin=[] stateslost=[] for state in states: statewise=df[df...
from Poke_game import * # Importa o módulo com a classe "Poke_game" from os import system # Importa a função system da biblioteca os def main(): # Define a função principal print('-'*20) print('PokeGame'.center(20)) print('-'*20) print('>>> Escolha um pokemón na lista abaixo e eu irei ...
import sqlite3 import grade class p7: def __init__(self,dbName): self.dbName=dbName self.db=None def load(self): self.db=sqlite3.connect(self.dbName) print 'database open ok' def save(self): self.db.close() print 'database close ok' def listBefore(self): cur = self.db.cursor() cur.execute("sele...
n=5 z=1 k=1 for i in range(1,n+1): for sp in range(n-i,0,-1): print(" ",end="") for j in range(1,k+1): print(z,end="") print() z+=1 k+=2
n=int(input("enter the decimal number: ")) hex_val='' while n: rem=n%16 if rem<=9: hex_val+=chr(48+rem) else: hex_val+=chr(55+rem) n=n//16 print(hex_val[::-1])
#1stmethod ##n=5 ##s=bin(n) ##res=0 ##for i in s[2:]: ## if i=="1": ## res+=1 ##print(res) #2nd_method ##n=5 ##res=0 ##c=0 ##while n: ## if n%2!=0: ## res+=1 ## n=n//2 ##print(res) #3rd_method n=15 res=0 while n: n=n&(n-1) res+=1 print(res)
class Node: def __init__(self, parent, value): self.values = [value] self.parent = parent self.children = [] def __repr__(self): returnstr = "Node: " for i in range(len(self.values)): returnstr += str(self.values[i]) + " " returnstr += " (has " + str(len(self.children)) + " children)"...
from Database import * class Node: def __init__(self,value): self.next=None self.value=value def __str__(self): return self.value class Stack_base (Database): """The class stack uses the LIFO (Last in, first out) principle""" def __init__(self): self.first=None self.size=0 def push(self,value):...
# 数据结构 # 线性表 # 双向链表 # 前驱结点和后继结点 # 有两个链接域prev与next,链接到前驱结点与后继结点 class SingleNode(object): """结点""" def __init__(self, item): self.elem = item self.next = None self.prev = None class DoubleLinkList(object): """...
import pandas as pd import numpy as np # Data Aggregati 数据聚合与分组运算 # 10.1 GroupBy 机制 # 分组运算:split-apply-combine # 分组方式有很多 df1 = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'], 'key2': ['one', 'two', 'one', 'two', 'one'], 'data1...
class Animal: """A generic animal""" def __init__(self, food_need, water_need, name): self._weight = 0 self._days_growing = 0 self._growth_rate = 1 self.food_need = food_need self.water_need = water_need self._status = 'Baby' self._type = 'Generic' ...
minutes=105 print(minutes%60) def countdown(n): if n==0: print ("blastoff") else: print (n) countdown(n - 1) countdown(4) def print_n (s,n): if n<=0: return print(s) print_n(s,n-1) print_n("a",1) name=input("what is your name")
memo = [0, 1, 1] def fib(index): pos = len(memo) - 1 while pos < index: memo.append(memo[pos] + memo[pos - 1]) pos += 1 if __name__ == "__main__": while True: response = input("Would you like to get a number in the fibonacci sequence? (Y/n) ") if response.lower() == "n": ...
from enum import Enum import random class Mood(Enum): HAPPY = 'happy' SAD = 'sad' MAD = 'mad' class Character: def __init__(self, name, color, mood, size): self.name = name self.color = color self.mood = mood self.size = max([0, min([300, size])]) self.health = 100 self.quotes = [] ...
# A very brief overview class Person(object): # Inherit the root class, object # Method = function declared within a class block # First positional parameter is always the instance, traditionally named "self" (vs. "this" in Java or C++) def __init__(self, first_name, last_name): self.SPECIES = "Hom...
# Advanced Python starts to look like functional programming, # using fewer statements and more expressions without side effects. from random import randint from itertools import ifilter, permutations long_list = [randint(0, 100) for i in xrange(100)] # ifilter(predicate callable, iterable) -> iterates over iterable...
# Split a string into a list of strings # Split on commas # Note that the separator is NOT included in the resulting strings. header = "Year,,University Name,Student Classification,Resident Status,Headcount" print header.split(',') # Split on commas, maximum 2 splits i.e. the sequence will contain at most 3 elements ...
# UPDATE combines elements of INSERT and SELECT: # UPDATE <TableName> SET <Column> = <Value> WHERE <predicates> # If the WHERE clause is present, only update those rows that satisfy the predicates. # If the WHERE clause is absent, update all rows. SQL = (''' CREATE TABLE Track ( TrackId INTEGER PRIMARY KEY AUTOINC...
import csv # Thus far we've only read files from the current directory: with open('regents.csv') as f: for line in f.readlines(): pass # implicit f.close() here # Alternatively: f = open('regents.csv') try: for line in f.readlines(): pass finally: f.close() # We've used the csv librar...
# Create different tables for categorical columns. # This is likely what the/a source relational database for the CSV looks like. import csv import sqlite3 conn = sqlite3.connect('salaries.sqlite') try: try: cur = conn.cursor() for drop_table_sql in ( 'DROP TABLE IF EXISTS Department;', 'DROP TAB...
from decimal import Decimal # Arbitrary-precision floating point # https://en.wikipedia.org/wiki/Floating_point # The Python float type is backed by a C double (64-bit) # Potentially imprecise but faster because its operations are in hardware x = 1.03 - .42 print "Fixed-width floating point result %0.20f" % x print # ...
# Occasionally a parent class will provide methods for its # This is generally called "protected" access and is denoted by a # single _ prefix, in contrast to the double __ prefix of "private" # access. # Unlike private access, protected access is not enforced by the language. # It is solely a convention. class Person...
class CardTests(unittest.TestCase): ## Test that if you create a card with rank 12, its rank will be "Queen" def test_cardrank(self): c = Card(rank=12) self.assertEqual(c.rank,"Queen") ## Test that if you create a card with rank 1, its rank will be "Ace" def test_cardrank1(se...
def letras_favoritas(letra, frase): tamanho = len(frase) quant = 0 for n in range(0, tamanho): if frase[n].lower == letra.lower: quant += 1 print('Sua letra favorita é a letra {} e ela aparece {} vezes na frase "{}"'.format(letra.upper(), quant, frase)) letra = input('Sua letra favo...
""" This module allows all objects in the programm to have a position This position is encapsulated in an independant class. That will allow us to use methods directly to those positions.""" import config.settings as constants class Position: """generate object's position """ def __init__(self, x, y): ...
def get_parents(child, classes): parents = set() def find_parents(child): if child not in classes: return for cls in classes[child]: parents.add(cls) find_parents(cls) return find_parents(child) return parents classes = {} exceptions = [] f...
#!/usr/bin/python3 import sys import os import math import struct def print_help(): """Print help message""" print(""" Usage: {:s} [OPTIONS] [INPUTFILE] OPTIONS -d DELIM, --delimiter DELIM Print DELIM between words. Defaults to newline --dice You will be asked to input results of die rolls as ran...
n=int(input("Enter number of rows")) b=int(input("Enter 1 or 0")) b=bool(b) for i in range(n): for j in range(n): if j<=i and b: print("*",end="") elif j<=n-1-i and not(b): print("*",end="") else: print("",end="") print("") """ **** 0 *** 1 ...
#!/usr/bin/python3 import threading import time def print_time(threadName,delay): count = 0 while count < 3: time.sleep(delay) count += 1 print (threadName,time.ctime()) class MyThread(threading.Thread): def __init__(self,name,delay): threading.Thread.__init__(self) self.name = na...
import sys sys.setrecursionlimit(20000) # Get our coin set stringCoinSet = open("coins", "r").readline().strip().split(' ') # Convert to integers coinSet = [] for stringCoin in stringCoinSet: coinSet.append(int(stringCoin)) # Get the change we must give back change = int(sys.argv[1]) # Recursive Programming Solu...
from __future__ import print_function from .distributions import Distribution class Deterministic(Distribution): """ Deterministic distribution (or degeneration distribution) Examples -------- >>> import torch >>> class Generator(Deterministic): ... def __init__(self): ... ...
from art import logo def add(n1, n2): return n1 + n2 def minus(n1, n2): return n1 - n2 def divide(n1, n2): return n1/n2 def multiply(n1, n2): return n1*n2 #key operations keys = { "+": add, "-": minus, "/": divide, "*": multiply } def calculator(): print(logo) num1 = float(input("enter yo...
#Class functions class cars: def __init__(self,name,speed,year,price): self.name = name self.speed = speed self.year = year self.price = price def car_features(self): return 'The car of choice is {} with speed of {} for the year {} total cost amounting to {}'.fo...
def matrix_size_check(*matrix_variables): return (len(set(len(a) for a in matrix_variables))) == 1 & (len(set(len(a[0]) for a in matrix_variables))) == 1 def matrix_addition(*matrix_variables): if matrix_size_check(*matrix_variables) == False: raise ArithmeticError return [[sum(t) for t in zi...
# # #vector간 덧셈을 실행하여 결과를 반환함, 단 입력되는 vector의 갯수와 크기는 일정하지 않음 def vector_size_check(*vector_variables): return len(set(len(a) for a in vector_variables)) == 1 def vector_addition(*vector_variables): if vector_size_check(*vector_variables) == False: return "ArithmeticError" return ([sum(t) for t in zi...
from math import * from random import * class Archer: """Records an archer's minimum, maximum, and average score for each end.""" def __init__(self, qual_score): self.max_end = 30 self.average_end = round((qual_score / 24),2) self.qual_score = qual_score self.min_end = self.dete...
import random def guessing_game(): random.seed() tries = 0 number_to_guess = random.randint(0, 100) guessed_number = None while number_to_guess != guessed_number or guessed_number is None: try: guessed_number = int(input("Enter number:")) except ValueError: ...
import matplotlib.pyplot as plt year = [1950, 2000, 2050, 2100] pop = [2.53, 6.13, 9.55, 10.85] # Line plot plt.plot(year, pop) # Define horizontal and vertical axis plt.show() # Show the plot year = [1800, 1850, 1900] + year # Add data to show population explosion pop = [1.0, 1.262, 1.650] + pop plt.fill_between(...
def substitute_vowels(lst): '''Zastepuja samogloski znakami "*"''' replaced = [] vowels = ['a', 'ą', 'e', 'ę', 'i', 'o', 'ó', 'u', 'y'] for word in lst: for vowel in vowels: word = word.replace(vowel, '*') replaced.append(word) return replaced def substitute_vowels2(ls...
# Create a 5 x 5 matrix using a list of lists matrix = [[col for col in range(5)] for row in range(5)] # Print the matrix print(matrix) # Create a num pairs nums = [(num1, num2) for num1 in range(5) for num2 in range(5)] print(nums) # Create a list of strings fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'l...
class PopulationSessionFactory(): """ Abstract factory class for creating PopulationSession objects for communicating with a Population Service and/or underlying algorithm. """ def create_session(self, population_service_host, population_service_port, ...
import re from past.builtins import basestring from servicecommon.parsers.parser import Parser from servicecommon.parsers.string_parser import StringParser class ListParser(Parser): """ Class which can parse a list of the values from a list in a single String, returning a List as the result. The b...
#CREAR #Una función que convierta grados Celsius a grados Farenheit #Una función que convierta grados Celsius a grados Kelvin #uario debe ingresar una temperatura en grados Celsius y el programa debe mostrar las conversiones a Farenheit y Kelvin utilizando las funciones. Si la temperatura ingresada es inferior al cero ...
#This programm contains show you all operators for understanding. #Arithmetic Operator #Already Defined variable value a=-10 b=20 #Additio...
""" Task 17: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example: Input: ...
""" Task 13: Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. """ class Solution: #def findMaxLength(se...