text
stringlengths
37
1.41M
#!/usr/bin/python3 import math contents = [] print("please input a set of instruction:") while True: try: a = input("") except EOFError: break contents.append(a) x = 0 y = 0 distant = 0 for value in contents: new_value = value.split(" ") if new_value[0] == "UP": y += ...
#!/usr/bin/python3 """input plaintext and shift""" plainText = input("Insert your ciphertext: ") shift = int(input("Enter your shift: ")) """decrypt function""" def decrypt(plainText, shift): cipherText = "" for ch in range(0, len(plainText)): if (ch + shift) < len(plainText): cipherText +...
phrase = "Phrase en camel case" phrase_split = phrase.split() resultat = [phrase_split.pop(0).lower()] for mot in phrase_split: resultat.append(mot.capitalize()) resultat_formate = "".join(resultat) print(resultat_formate)
# https://adventofcode.com/ # # Implementation of the challage intcode computer as a class as it was needed for challenge 7 # import unittest def get_program( filename ): with open( filename ) as fp: line = fp.readline() prog = [] for d in line.strip().split(","): prog.append(i...
class CardGame: def __init__(self): self.deck = Deck() self.deck.shuffle_v2 class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(1,14): self.cards.append(Card(suit, rank)) def print_deck(self): ...
import turtle import random def tree(branchLen,t, thickness, colorN): if branchLen > 5: color = ["green", "red", "yellow", "blue"] if colorN >= len(color): colorN = len(color) -1 t.color(color[colorN]) angle = random.randrange(15, 45) subBranch = random.randrange...
from linkedlist2 import Node class ImprovedQueue: def __init__(self): self.root = None self.last = None self.length = 0 def is_empty(self): return self.length == 0 def insert(self, data): node = Node(data) if self.root == None: self.root = self.la...
testArray = [31, -41, 59, 26, -53, 58, 97, -93, -23, 84] def maxSubarray(array): maxEndingHere = maxSoFar = array[0] maxBegin = maxEnd = 0 for i in range(1, len(array)): print('i is: {}\nvalue of i is: {}\nmaxEndingHere is: {}\nmaxEndingHere + i is: {}'.format(i, array[i], maxEndingHere, maxEndingH...
import numpy as np def normalize(X, mu, sigma): """Returns a normalized matrix. Subtracts average and divides by standard deviation. """ return (X - mu) / sigma
#!/usr/bin/env python # coding: utf-8 # In[8]: i=1 while(i<5): print(i) i+=1 # In[9]: i=1 while(i<=5): print(i) if i==3: break i+=1 # In[10]: i=1 while(i<=5): i+=1 if i==3: continue print(i) # In[11]: def funcexample(): print("This is a sample function") funcexam...
class Team(object): """Football team""" def __init__(self, name: str): self.name = name self.W = 0 self.D = 0 self.L = 0 @property def MP(self) -> int: return self.W + self.D + self.L @property def points(self) -> int: return 3 * self.W + self.D ...
def recite(start: int, take: int = 1) -> list: """List the famous beer song""" song = list() for i in range(start, start-take, -1): if i == 0: song.append("No more bottles of beer on the wall, " "no more bottles of beer.") song.append("Go to the store ...
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from itertools import permutations def parse_input(data: Iterator[str]) -> Iterator[tuple[list[str], list[str]]]: """Data is split into input and output, each containing a list of corresponding segments""" for line in ...
from itertools import count class Primes(object): """Iterable primes using Sieve of Eratosthenes""" def __init__(self, end=None): if not isinstance(end, (int, None)): raise ValueError(f'Not a valid end ({end})') self.numbers = count(2) self.end = end def __iter__(self)...
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from functools import reduce from numpy import sign class Field: """A simple field (or grid) for drawing lines and accumelating overlapping coords. With a method `add` for adding a range of points.""" def __init__(self,...
from string import ascii_uppercase from string import digits from random import randint from itertools import product class Robot(object): """Creates a Robot with a random name, e.g. XE137""" def __init__(self): self.NAMES = [''.join(char + dig) for char, dig in product( product(...
def deviders(number: int) -> int: """Generates all deviders for a given number""" for i in range(1, number // 2 + 1): if number % i == 0: yield i def classify(number: int) -> str: """Determine the class of a number""" if number <= 0: raise ValueError("Error: positive intege...
#!/usr/bin/python3 # A cenetic algorithm for finding the key # in a mono-alphabetic substitution cipher import string import sys import re from random import randint from random import shuffle from random import choice MAX_GENERATIONS = 1000 # Max number of generations MAX_BEST_KEYS = 20 POPULATION_SIZE = 20 # M...
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from math import ceil, floor def calc_cheapest_horz_position(data: Iterator[str]) -> int: """Finds a point which requires all points in a given input to travel the least amount of distance combined""" positions = list(s...
#!/usr/bin/env python3 from argparse import ArgumentParser from typing import Iterator from numpy import prod class Cloud: """A helper class for easily retrieving data and checking conditions from a grid like data structure.""" def __init__(self, data: Iterator[str]): self._cloud = [[int(i) for i ...
class Solution: # @return a string def convert(self, s, nRows): if not s or nRows <= 1: return s res = '' for si in range(nRows): for i in range(si, len(s))[::2 * nRows - 2]: res += s[i] if si > 0 and si < nRows - 1 and i - 2 * si + 2 * nRows - 2 < len(s): res += s[i - 2 * si + 2 * nRows - 2]...
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree node # @return nothing def connect(self, root): if not root: return next_node = No...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): def sort_list(list_a, list_b): if not list_a: return list_b elif not list_b: return list_a ...
class Solution: # @return a boolean def isValid(self, s): stack = [] for c in s: if c in ['(', '[', '{']: stack.append(c) else: if not stack: return False if c == ')' and stack.pop() != '(': return False elif c == ']' and stack.pop() != '[': return False elif c == '}' and ...
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return an integer def __init__(self): self.max_sum = -10000000 def maxPathSum(self, root): def iter(root): if root == None: r...
""" Some of this code is based on the tutorial at http://ischlag.github.io/2016/06/19/tensorflow-input-pipeline-example/. This is sort of an extension of that blog post to a full example of using Tensorflow's Readers, Queues, etc., for training a CNN on MNIST Author: Patrick Emami """ import os import tensorflow as ...
import colorsys import pandas as pd import numpy as np import logging import re def hex_to_rgb(hex_color: str) -> list: """Converting hexadecimal color to rgb params: hex_color (str): color represented in hexadecimal format eg '#FFFFFF' returns: list: RGB color representation, list with 3...
import turtle import math turtle.shape('turtle') turtle.shapesize(1) turtle.speed(10000000) turtle.penup() turtle.forward(200) turtle.left(90) def arc(theta, r): turtle.pendown() for i in range (theta//3): turtle.forward(2*(math.pi)*r/(360/3)) turtle.left(3) turtle.pen...
'''2. Write a python program to input the temperature of a user in degree celcius and convert it into farenheit.''' #Taking values from the user celsius = float(input('Enter temperature in celsius: ')) #Calcuate Temperature in Fahrenheit fahrenheit = (celsius*1.8)+32 print("The temperature in Fahrenheit is: ", fa...
class Node: '''Created by krishna kant sharma B.tech 3rd year ''' def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def printList(self): temp = self.head while temp: print(temp...
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... import platform from functools import reduce import time import sys if sys.platform == 'win32': default_timer = time.perf_counter e...
from misc.titlecase import titlecase def getWOSValues (): """ read WOS values from a file (normalizing on the way) """ path = '../uniqueWOSvalues_pubname.txt' s = open(path).read() raw = s.split('\n') values = [] for v in raw: if not v.strip(): continue values.append(normalizeItem (v)); return values ...
''' Initial thought process Okay so this program's purpose is to help a sick workaholics remind themselves that they must take a break. Step 1. get current time Step 2. From Current time it goes off every X amount of time e.g 30 mins Step 3. Get the time current time + x amount of time Step 4. As current time updates a...
#Christian Walker #9/12/2019 #Meal, Tip, and Tax Calculator #A program that calculates the total amount #of a meal purchased at a restaurant #Intro print("Hello!, Welcome to the Meal, Tip, and Tax Calculator") print("All percentages should be entered in the following format: '.xx'") print("-------------------...
x = 4.33 y = 2.33 z = x * y #sep='' removes spaces from print funtions print("The value of z is:",z,".") #The value of z is: 10.0889 . print("The value of z is:",z,".",sep='') #The value of z is:10.0889. print("The value of z is:" +str(z) +".") #The value of z is:10.0889. print("The value of z is:",...
"""mystring = 'McGill' print(mystring) print(mystring.lower()) """ #_________________________________________________________________________________________________________ """mystring = 'McGill is my university' mystring_split = mystring.split(' ') print(mystring_split) """ #________________________________________...
input = open("input.txt", "r"); frequency = 0 for line in input: frequency += int(line); print(frequency)
from coins.coin_types import CoinTypes class CoinsTable: max_coins_count = 7 max_any_color_count = 5 def __init__(self): self.coins_count = { CoinTypes.WHITE : CoinsTable.max_coins_count, CoinTypes.BLUE : CoinsTable.max_coins_count, CoinTypes.GREEN :...
import pandas df1 = pandas.DataFrame({"col1": [1, 5, 9], "col2":[2, 6, 0]}) #print(df1) df2 = pandas.DataFrame({"col1": [11, 15, 19], "col2":[21, 61, 10]}) #print(df2) df1.loc[df2.index[0]] = df2.iloc[1] #print(df1) print(df2.shape) for row in df2.iterrows(): df1.loc[df1.shape[0]] = row[1] print...
x= int(input("ingresa un numero X \n")) y= int(input("ingresa un numero Y \n")) div=x%y if div == 0: print("Es entero") else: print("NO es entero") print("2--------------------\n") a= int(input("ingresa un numero a \n")) b= int(input("ingresa un numero b \n")) if a<b : print("El numero mayor es"+ str(b)...
#!/usr/bin/python #-*- coding: utf-8 -*- x= int(input("ingresa un numero X \n")) y= int(input("ingresa un numero Y \n")) print(type(x)) if x == 3 and y == 3: print("se cumplio AND") else: print("NO") if x == 3 or y ==3: print("se cumplio OR") else: print("NO")
"""un/comment to de/activate ########################### # types # int, float # bool # < > <= >= == != # not, and, or # str # None # abstractsions # variables # functions # classes # control flow # if, elif, else # if <condition>: <consequent> # iteration # fo...
"""un/comment to de/activate ########################### # data types # int, float # + - * / // % ** # bool # == != < > <= >= # not, and, or # in # str # None # list # indexing / subscripting / slicing # .append # len, range # in # a...
"""un/comment to de/activate ########################### # python overview # data types # int, float # bool # None # str # list # discribe mutability vs immutability # abstractions # variables # functions # control flow # if, elif, else # iteration # for # while ###...
from tkinter import * from PIL import ImageTk, Image import speech_recognition as sr from tkinter import messagebox from control.VoiceController import VoiceController class MainView: def exit(self): exit() def load(self): self.main=Tk() self.main.ti...
#import the xlrd module import xlrd import xlwt #Open the spreadsheet file (or workbook) workbook = xlrd.open_workbook("Book1.xlsx") print("workbook nsheets : {0}".format(workbook.nsheets)) print("workbook sheet names : ", workbook.sheet_names()) first_sheet=workbook.sheet_by_index(0) print("row values : ...
def testmethod(test123): if test123 == 'Hi': return "Hi there" else: return 'Goodbye' returnedfromtest = testmethod('Hi') print(returnedfromtest) print("Hello world", end="\n test 123") a = True b = "How am I here?" print("\n", b[5:]) print(b[-5:]) print("\n", b[2], "\n") pr...
from collections import Counter lst = [] n = int(input("Enter number of elements : ")) for i in range(0, n): ele = input() lst.append(ele) lst for i in lst: names = i.split()[0] names ls = [] for i in lst: nm = i.split()[0] ls.append(nm) ls times = Counter(ls) rp = times.values() m...
""" This module creates a rudimentary form entering system within an ipython notebook and creates a food stack plot with the entered data. """ import ipywidgets as widgets from IPython.display import clear_output from stack_plotting import stack_plot, food_stack_plot # a list of lists of values to be plotted in eac...
import random import socket import string import threading import json from packet import Packet, PacketType """ Chat Room Client Completed: Feb.10.2020 Written By: Michael Nichol & Bobby Horth Purpose: The purpose of this application is to connect to a localhost server, a...
from plant import Plant class Tomato(Plant): 'This is the class that represents the tomato, being a child of class Tomato():' ######################################################## CLASS VARIABLES TOMATO_STAGES = ['Seedling','Growing','Flowering','Fruiting'] tomatoRid = 1 TOMATO_VARIETY = 'Fr...
nome1 = input("digite seu nome: ") nome2 = input("digite seu nome: ") idade1 = int(input("digite a sua idade:")) idade2 = int(input("digite a sua idade:")) print("concatenado:", nome1,"e",nome2) print("somando:", idade1 + idade2) # Comentário para commit
""" window.py -- Defines functions to window an array of data samples """ ### ADD YOUR CODE AT THE SPECIFIED LOCATIONS ### import numpy as np ### Problem 1.d ### def SineWindow(dataSampleArray): """ Returns a copy of the dataSampleArray sine-windowed Sine window is defined following pp. 106-107 of Bo...
def shout(word): if word == "french toast": return word.upper() elif word == "candy": return word else: return word.lower()
import threading i = 0 def increment_i(): global i for _ in range(1000*1000): i = i+1 def decrement_i(): global i for _ in range(1000*1000): i = i-1 def main(): # Configure threads increment_thread = threading.Thread(target=increment_i) decrement_thread = threading.Thr...
# Project Euler problem 98. import csv import re import numpy import itertools import string # Check if two strings are anagrams def isAna(st1, st2): return (sorted(st1) == sorted(st2)) # Read in data dat = [] with open('words2.txt','rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreade...
#Crie um programa que leia um número real qualquer e mostre na tela a sua porção inteira. #Autor: Daniel Marques from math import trunc print("\nARRENDODAMENTO SUPERIOR") a = float(input("\nNúmero: ")) print("\nPORÇÃO INTEIRA: {}".format(trunc(a)))
#Escreva um programa que pergunte a quantidade de kilômetros percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa 600 reais por dia e 0.15 reais por kilmetros rodados.^ print("\nALUGUEL DE CARROS") d = float(input("\nDias: ")) km = fl...
# Time: O(n) # Space: O(1) def reverse(string): return ''.join([string[i] for i in range(len(string)-1, -1, -1)]) # More Pythonic, and includes the null-termination # Time: O(n) # Space: O(1) def reverse(string): return string[-2::-1] + '\0'
# Time: O(n) # Space: O(n) def all_unique(string): character = {} for char in string: if character.get(char): return False return True # Time: O(n^2) # Space: O(1) def all_unique2(string): for i, char in enumerate(string): for other_char in string[i+1:]: if char ...
# Doubly Linked List Queue ''' In the Queue Adjust the tail when adding item Adjust the head when removing item ''' #n1 = bldg.head #lowest floor #n10 = bldg.tail #highest floor from node import DNode class Queue: def __init__(self): self.head = None self.tail = None ...
import os menu_print = "¿Qué desea hacer?\n1) Insertar Usuario\n2) Buscar Usuario\n3) Actualizar Usuario\n4) Eliminar Usuario\n5) Mostrar todos\n6) Salir del menú" #aux = {"cedula": 0, "nombre": "", "apellidos": "", "direccion": ""} menu = True def menu(seleccion:int): if seleccion ==1: insertar() elif...
import numpy as np matriz= [[4,3],[3,4],[6,8]] #filas y columnas m(i,j) for i in range(3): for j in range(2): print(matriz[i][j]) #numpy es una biblioteca para soporte de vectores y matrices en python # a.shape --> me da la longitud de la matriz-
from ConstraintSatisfactionProblem import ConstraintSatisfactionProblem class CircuitBoardProblem(ConstraintSatisfactionProblem): def __init__(self, variables, board, mrv=False, lcv=False, mac=False): self.variables = variables self.domains = self.build_domains(board) self.constraints = sel...
""" Module containing class DenseSymmMatrix representing a dense symmetric matrix and various operations on it. """ import numpy as np from numpy import linalg as la import time import copy import numbers from numbers import Number class DenseSymmMatrix(object): """ Class for dense symmetric matrix """...
import numpy as np import math #from Location import Location def get_random_location(): return [np.random.uniform(-90, 90), np.random.uniform(-180, 180)] def get_distance_between_two_locations(location1, location2): """ To get the distance between two locations. We use the 'haversine' formula to calculate the ...
'''Detector de velocidade''' print('lembrando que a velocidade máxima permitida é de 60km/h') vel = float(input('Digite a velocidade do veículo: ')) exc = vel - 60 multa = exc * 7 if vel >60: print('O veículo recebeu uma multa de R$7,00 por kilômetro ultrapassado') print('Sua multa foi de R${} re...
import numpy as np a=np.array(input('Enter any array:')) b=np.array(input('Enter another array:')) c=np.linalg.det(a) print('Det of a matrix a',c) d=np.linalg.matrix_rank(a) print('Rank of a matrix a',d) e=np.trace(a) print('Trace of a matrix a',e) f=np.linalg.inv(a) print('Inverse of a matrix a',f) g=np.linalg.eigval...
#an implementation of the single-dimensional parity check #by: Rayven Ingles, BSCS 4 #completed as a lab exercise for CMSC 137 def check_input(input_string) : ###loop through input string### for character in input_string: if not (character == "0" or character == "1"): print("Input m...
# Task: we've created Series containing the various variables we've been looking at this lesson. # Pick a country you're interested in and make a plot of each variable over time %pylab inline import pandas as pd import seaborn as sns #import matplotlib.pyplot as plt employment = pd.read_csv('/home/hayley/Documents/Da...
import pandas as import pd countries = [ 'Afghanistan', 'Albania', 'Algeria', 'Angola', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', ] employment...
a = '3' b = '1' c = 6 d = 2 if b > a: print(c + d, end=',') print(a + b) else: if a == b: print(a, d) else: print(a,b,c,d, sep='')
from tkinter import * from tkinter import messagebox #funciones def agregar(): print() #UI ventana = Tk() nombrePeluche = StringVar() cantidadPeluche = IntVar() precioPeluche = DoubleVar() ventana.geometry("400x400") ventana.title("Peluchitos.com") tituloLabel = Label(ventana, text="Peluchitos.com...
food='カレーライス' if 'カレー' in food: print('カレーが含まれています') food2='すし' if not 'カレー' in food2: print('カレーが含まれていません') if 'カレー' not in food2: print('カレーが含まれていませんね') score=80 if 60 < score < 80: pass isError=False n=50 if isError==False and n<100: pass num=2 if num%2==0: print('偶数') aisatsu='さようなら'...
def sumof2(n): return sum(range(1,n+1)) def sumof3(n): if n <1: return n else: return n+sumof3(n-1) num=int(input('正の整数')) ans=sumof3(num) print(ans)
is_awake=True count=0 while is_awake == True: count +=1 print('ひつじが{}匹'.format(count)) key=input('もう眠りそうですか?(y/n)>>') if key =='y': is_awake=False print('おやすみなさい')
import random as r i=0 input('Enterで対決開始[Enter]') while True: you_dice=[r.randint(1,6) for i in range(3)] pc_dice=[r.randint(1,6) for i in range(3)] print('あなたの出目') print(you_dice) print('コンピューターの出目') print(pc_dice) you_sum=0 pc_sum=0 for i in range(len(you_dice)): you_sum+=...
def eat(breakfast,lunch='ラーメン',dinner='カレー'): print('朝は{}を食べました'.format(breakfast)) print('昼は{}を食べました'.format(lunch)) print('夜は{}を食べました'.format(dinner)) print('8月1日') eat('トースト','おにぎり') print('8月2日') eat('トースト',dinner='やきそば') print('8月3日') eat('バナナ','そば','焼肉') print('8月4日') eat('トースト')
ages=[28,50,8,20,'ひみつ',78,25,'無回答',22,10,27,33] samples=list() for age in ages: if not isinstance(age,int): continue if 20 <= age < 30: samples.append(age) print(samples)
import random COINS=200 TW=5 table=[] def createTable(): global table table=[[random.randint(0,9) for j in range(TW)]for i in range(TW)] for row in table: print(row) #createTable() def countBingoLine(): global table vertical=[[table[j][i] for j in range(TW)]for i in range(TW)] cross...
#! /usr/bin/python print "Hello" printLine = """ Printing the whole text without changing the indentation. printing multiple lines without changing anything """ print printLine calculation = 10 + 2 - 3 / 2 print "Calculation is : %d " % calculation def function1(myString, myNum): print "String sent to function ...
#! /usr/bin/python number = [1, 2, 3, 4, 5] fruits = ['apple', 'orange', 'papaya', 'grapes', 'banana'] change = [1, 'roti', 2, 'kapda', 3, 'makan'] for num in number : print "Number is %d" % num for fruit in fruits : print "Fruit currentley selected is : %s" % fruit for i in change : print "I is %r" % i element...
# Name: Max Voisard # Class: Programming with Python CIT248S # Date: 4/4/2017 # Assignment: Chapter 9 Programming Challenge roomNumber = {'CS101':'3004', 'CS102':'4501', 'CS103':'6755', 'NT110':'1244', 'CM241':'1411'} # Creating dictionary for course number's room numbers instructor = {'CS101':...
# Name: Max Voisard # Class: Programming with Python CIT248S # Date: 4/11/17 # Assignment: Chapter 10 Programming Exercise class Item: def __init__(self, description, units, price): # init method self.__description = description # Instantiating objects self.__units = un...
import time from binary_search_tree import BinarySearchTree start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # names_1 = sorted(names_1) # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # names_2 = sorted(names_2) # List contain...
from re import search def getFilenameAndExtensionFromPath(path): return search("(\w+)\.(\w{3})", path).groups() def replaceFilenameAndExtensionFromPath(path, filename, extension): # Get the path without the filename oldFilename, oldPath = getFilenameAndExtensionFromPath(path) path = path[0:-(len(oldF...
#1 #browse option # Python program to extract text from all the images in a folder # storing the text in corresponding files in a different folder from PIL import Image import pytesseract as pt import os def main(): # path for the folder for getting the raw images path ="E:\\mucomputer\\ima...
#list down Error #Name error list = 12 print(list1) #2 #TYpeError a = '123' a+= 123 #3 #TypeError l = [1,2,3,4,5,6] for i in range(2,1): print(i+1) #4 #syntax Error for i range(1,10): print(i) #5 #index error l = [1,2,3.4,5,56,7] for i in range(len(l)): print(l[i+1]) #6 #module not fount error import mod...
""" Mad Libs are stories with blank spaces that a reader can fill in with their own words.""" #informing the user the program has started print "Mad Libs is starting!" name = raw_input("Enter a name: ") adjective1 = raw_input("Enter an adjective: ") adjective2 = raw_input("Enter another adjective: ") adjectiv...
import time class Logger: def __init__(self, path, mode): self.path = path self.mode = mode def __enter__(self): self.file = open(self.path, self.mode) return self def write(self, value): self.file.write(f'{time.ctime()} {value}\n') def __exit__(self, exc_type...
import re def validate_passports_with_data(): with open('input.txt') as fin: input_list = fin.readlines() text_lst = [i.replace("\n", "") for i in input_list] required_fields = ["byr","iyr","eyr","hgt","hcl", "ecl","pid"] passport_list = [] temp_list = [] ...
def map_traverse_trees(): with open('input.txt') as fin: input_list = fin.readlines() text_lst = [i.replace("\n", "") for i in input_list] tree_map = [list(i) for i in text_lst] num_cols = len(tree_map[0]) num_rows = len(tree_map) trees = 0 pos = [0,...
from .Word import Verb, Adjective u_te_dict = {'す': 'して', 'く': 'いて', 'ぐ': 'いで', 'ぶ': 'んで', 'む': 'んで', 'ぬ': 'んで', 'る': 'って', 'つ': 'って', 'う': 'って'} def formName(): return "Te" def toolTip(): return "Te Form: 食べて/飲んで" def wordGroups(): return ["verb", "adjective"] def hasFormalities(): r...
# -*- coding: utf-8 -*- """ Created on Tue Mar 3 14:37:28 2020 @author: Dan_B """ import matplotlib.pyplot as plt #from scipy.stats import binom import numpy as np """plt.plot([0,0,1,3,0,5], 'ro') plt.axis([-1,10, 0, 20]) plt.ylabel('some numbers') plt.show()""" choice = int(input("choose the distribution")) minli...
#! /usr/bin/env python3 # -*- coding: utf8 -*- import random import pygame from pygame.locals import * pygame.init() class Maze: def __init__(self): self.tiles = Maze.make_level() self.count = 0 @staticmethod def make_level(): """Load the level and add 3 objects under random pos...
import cv2 ##import the module img = cv2.imread("Sample.jpg") ##read your image y = 0 ##HEIGHT from x = 0 ##WIDTH from h = 300 ##HEIGHT w = 510 ##WIDTH crop_image = img[x:w, y:h] cv2.imshow("Cropped", crop_image) ##display Cropped image cv2.waitKey(0)
text="ahmed elnakeeb" words=word_tokenize(text) for word in words : spell = SpellChecker() print (spell.correction(word))
dur = int(input("Введите количество секунд:")) if dur >= 0 and dur <= 59: print(str(dur) + " sec") elif dur >= 59 and dur <= 3599: print((str(dur // 60) + " min") + " " + (str(dur % 60) + " sec")) elif dur >= 3600 and dur <= 86399: print(((str(dur // 3600) + "h") + " " + (str(dur % 3600 // 60)) + "min") +...
class Car: def __init__(self, speed, color, name, is_police): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): print('GO!') def stop(self): print('STOP!') def turn(self, direction): print(f'Turn {...
# -*- coding: utf-8 -*- """ Created on Tue Feb 13 09:23:41 2018 @author: patemi """ # https://chrisalbon.com/python/data_wrangling/pandas_dropping_column_and_rows/ import pandas as pd import os.path import numpy as np from functools import reduce path = '\\\\apw-grskfs01\\GVAR2\\Global Risk Management...