text
stringlengths
37
1.41M
import itertools from heapq import heapify, heappush, heappop # A priority queue implementation based on standard library heapq # module. Taken from https://docs.python.org/2/library/heapq.html, but # encapsulated in a class. Also iterable, printable, and len-able. # TODO some extra capabilities that would be nice: ...
class Aditya: def __init__(self, L = "Aditya"): self.__lst = L class __makeIter: def __init__(self, L = "Aditya"): self.__idx = 0 self.__L = L def __next__(self): if self.__idx >= len(self.__L): raise StopIteration else: self.__idx += 1 return self.__L[self.__idx-1] def __iter__(self):...
class BinaryTree: def __init__(self,data, left = None, right = None): self.data = data self.left = left self.right = right def getCode(self, char): if self.left == None and self.right == None: if self.data == char: return "" else: return None if self.left != None: LT = self.left.getCode(cha...
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " def encode_string(codestring, plaintext): encodedStr = "" plaintext = plaintext.upper() for x in plaintext: if x == " ": encodedStr += "-" elif (x in alphabet) == False: encodedStr += x else: encodedStr += codestring[alphabet.index(x)] return encodedStr def ...
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.index = 0 self.queue = [] def append(self, item): # if the queue is smaller than capacity (5 in this) if len(self.queue) < self.capacity: # add the item to the back self...
import random class User: """ Class that generates new users """ user_list = [] def __init__(self, username, password): """ the__init__ method define properties for the object """ self.username = username self.password = password def save_user(self): ...
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ divisible = False num = 2520 while divisible == False: divisible = True for i in range(...
# 3)For “Fare” columns in Titanic data find # a) maximum, minimum # b) mean # c) mode # d) median # and # f) Draw the graph boxplot #******************************************** import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy import stats #from scipy import stats plt.s...
import sys primeCache = {} def isPrime(n): if n in primeCache: return primeCache[n] else: primeCache[n] = isPrimeCalc(n) return primeCache[n] def isPrimeCalc(n): if n < 2: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False candidateDivi...
# Method1: use convergence recurrence and e's pcf to get 100th and then sum numerator import sys def getPCFe(k): if k % 3 != 2: return 1 else: return 2 * (k+1) // 3 def getConvergentNumerator(k): aPenult = 1 aUlt = 2 for k in range(1, k): aNew = getPCFe(k) * aUlt + aPenult aPenult = aUlt ...
def digitSum(n): return sum(map(int,list(str(n)))) greatest = 0 for a in range(1, 100): num = 1 for b in range(1, 100): num *= a greatest = max(greatest, digitSum(num)) print(greatest)
Nombre = input("gregar nombre") Apellido = input("agregar apellido") Ubicacion = input("agregar ubicacion") Edad =input ("agregar edad") edad =input ("agregar edad") if edad >= "18": print("mayor de edad") else: print ("menor de edad") print("hola te llamas",Nombre,"tu apellido es",Apelli...
import sys import re import os import argparse defines = [] # Stores all the constants have been defined # Pattern that finds magic numbers pattern = "(?<![a-zA-Z_])([-+]?\d*\.\d+|\d+)(?![a-zA-Z_])" script_path = os.path.abspath(__file__) script_dir = os.path.split(script_path)[0] def firstPass(file): """ Passes ov...
x = 2.3 y = 3.1 z = 1.6 mew = (x*x)+(y*y)+(z*z) print("x = "+str(x)) print("y = "+str(y)) print("z = "+str(z)) print("(x*x)+(y*y)+(z*z) = "+str(round(mew))) print("สมการ x²+y²+z² = "+str(round(mew)))
x = input('Number:') if int(x) < 0: print("positive") elif int(x) == 0: print("zero") else :print("negative")
import random y = random.randrange(10) z = 0 while z <= 2: x = input('Number:') if int(x) == y: print("!!!!!!!!!YOU WINNNN!!!!!!!!!!!") break elif int(x) > y: if z==2: print("GAME OVER"+" random = "+str(y)) break else :print("too big") ...
# This is the original version of the project. For the more modern lesson version, see "learn it">final.py import os import random import time import platform version = "0.6" lb = "-----------------------------------------------------------------------------" def lbl(): print(lb) def br(): print(" ") def wai...
def sort(arr): swap = True while swap: swap = False for i in range(len(arr)-1): if arr[i] > arr[i+1]: x= arr[i] arr[i] = arr[i+1] arr[i+1]=x swap = True arr = [] n = int(input("Elements : ")) for i in range(0, n): ele = int(input()) a...
# initialize 10 to the variable of types of people types_of_people = 10 # initialize a string variable and insert the variable of types_of_people between the variable x x = f"There are {types_of_people} types of people." # initialize a string variable binary = "binary" # initialize a string variable do_not = "don't" # ...
# write functions with parameters def add(a,b): print("ADDING %d + %d" %(a,b)) return a+b def subtract(a,b): print("SUBTRACTING %d - %d"%(a,b)) return a-b def multiply(a,b): print("MULTIPLYING %d * %d"%(a,b)) return a*b def divide(a,b): print("DIVIDING %d / %d"%(a,b)) return a/b prin...
#!/usr/bin/env python3 my_set = set() print(my_set) print('ADD') A = { 1, 2, 3 } A.add(4) print(A) # UNION A = set([1, 2, 3, 4]) B = set([3, 4, 5, 6]) print(A | B) A = set([1, 2, 3, 4]) B = set([3, 4, 5, 6]) A.update(B) print(A) # INTERSECTION A = set([1, 2, 3, 4]) B = set([3, 4, 5, 6]) print(A & B) A = set([1, 2...
for i in range(6): print(i) print(list(range(6))) #name =input("please enter you name: ") #print(name) print(100*100) print(r'\\\\')#表示" "内默认不进行转义 #表示多行 print('''line1 line2 line3''') print(r'''hello\n \# 未进行转义 world''')#r" 内部未进行转义,表示\以后的转义无效 #bool运算符 age =19 if age >= 18: print...
# You are given the following data for agents  # agent # is_available # available_since (the time since the agent is available) # roles (a list of roles the user has, e.g. spanish speaker, sales, support etc.)  # When an issue comes in we need to present the issue to 1 or many agents based on an agent selection mode. ...
# A level Authentication Challenge class UserStore(): username = None validated = False #end class class User(): username = "" password = "" first_name = "" surname = "" #end class users = [] def encrypt_ceasar(password, key): #assumption - only lower case a-z lowest_c...
#!/usr/bin/env python """ List the english words having a french translation that differs from a single letter. $ python list_commonly_mispelled_words.py human,humain dinner,dîner """ if __name__ == '__main__': import json import Levenshtein from unidecode import unidecode with open('../../anki-us...
import os def print_frame_ranges(path): ''' Print animated sequences in 'path' in the following format: 'name: 1001-2000' if there are no gaps 'name: 1001, 1003-1500, 1600-2000' if there are gaps the format for an animated sequence is name.####.ext e.g. /job/.../my_render_v001.1001.jpg This function det...
# Instance Method - Mutator Method / Setter Method class Mobile: def __init__(self): self.model = 'RealMe X' # Instance Variable def set_model(self): # Mutator Method self.model = 'RealMe 2' realme = Mobile() # Before setting print(realme.model) # After Setting realme.set_model() # Calling M...
from datetime import datetime ct = datetime.now() # Calling Method using class name print("Current Date and Time:", ct) print("Date:", ct.day) print("Month:", ct.month) print("Year:", ct.year) print("Hour:", ct.hour) print("Minute:", ct.minute) print("Second:", ct.second) print("Microsecond:", ct.microsecond) print...
# Multitasking using Multiple Thread # Two task using Two Threads from threading import Thread class Hotel: def __init__(self, t): self.t = t def food(self): for i in range(1, 6): print(self.t, i) h1 = Hotel('Take Order From Table: ') h2 = Hotel('Serve Order to Table: ') t1 = Thread(target=h1.food) t2 = T...
# Instance Variable class Mobile: def __init__(self): self.model = 'RealMe X' # Instance Variable def show_model(self): # Instance Method print(self.model) # Accessing Instance Variable realme = Mobile() redmi = Mobile() geek = Mobile() print("RealMe:", realme.model) print("Redmi:", redmi.model) pr...
# Class Variable class Mobile: fp = 'Yes' # Class Variable @classmethod # Class Method def is_fp(cls): print("Finger Print:", cls.fp) # Accessing Class Variable realme = Mobile() redmi = Mobile() geek = Mobile() print("RealMe:", Mobile.fp) print("Redmi:", Mobile.fp) print("Geek:", Mobile.fp) ...
'''class Decorator(object): """Simple decorator class.""" def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print('Before the function call.') res = self.func(*args, **kwargs) print('After the function call.') return res @D...
n = int(raw_input()) for i in range (1,n+1): for j in range (1,i+1): print "*", print for i in range (1,n+1): for j in range (n,i-1,-1): print "*", print for i in range(1, n + 1): for j in range(1, i + 1): print i, print for i in range(1, n + 1): ...
import numpy as np #based off of the fact that we are dealing with discrete values, adjacency is just a specific type of intersection, so #I will be making a function to find adjacency but all adjacency would also trip intersections. Furthermore contained is #a type of intersection as well where all of it is in the ot...
import sqlite3 class Banco(): def __init__(self): self.conexao = sqlite3.connect('Database.db') self.createTable() def createTable(self): c = self.conexao.cursor() c.execute("""create table if not exists Clientes ( id INTEGER NOT NULL PRI...
import pickle from os import path class Customer(object): def load_customer_data(self, seat_book): """ This function is used to load customer data in pickle file. :param seat_book: Input parameter to load booked seat details :return: Nothing """ wit...
# asal sayi 1'e ve kendisine bolunen sayidir """ Asal sayi bulma cikmak icin q-e basin """ def asalmi(x): if x==1: return False elif x==2: return True else: for i in range(2,x): if x%i==0: return False return True while True: asal=input("Sayi:...
# -*- coding: utf-8 -*- """ Created on Thu Sep 8 19:18:19 2016 @author: Rachel Carrig; rlc63 """ #Overall Comment: Very good assignment! You covered all possible situations and commented well. But please include examples #to show that your functions really work. I have made a few comment with "Comment:" in front, you...
import json def takesurvey(questions, answers): answer = {} for q in questions: answer[q] = input(q) # print(answer) answers.append(answer) # print(answers) a = [] q = ['what is your name? ', 'What is your nationality? ', 'How old are you? ', 'What is your favorite ice cream flavor? ', ...
class Node: def __init__(self,data): self.left = None self.right = None self.data = data self.type = None class BinaryTree: def __init__(self): self.root = None def insert_node(self,root,element): if self.root is None: self.root = Node(element)...
#!/usr/bin/python # -*- coding: utf-8 -*- import random import math import sys # Read from the file u.user and return a list containing all of the # demographic information pertaining to the users. # The userList contains as many elements as there are users and information # pertaining to the user with ...
from classes.dictionary import Languaje class English(Languaje): def __init__(self): super().__init__() self.words = { 'article': { 'the', 'a', 'an' }, 'verb': { 'regular': { 't...
#XXX: begin from line 0 # index (mapping) from the line number, begin from 0 def index(text): index0 = {} i = 0 for line in xrange(len(text)): if text[line].startswith('@'): index0[i] = line i += 1 return index0 # from 1 to 2 def mapping(text): index0 = {} ind...
#input = raw_input("please enter file name : ") input = 'mbox-short.txt' try: file = open(input) except: print 'cant open file:' , input exit() total = [] count = 0 for word in file: word = word.rstrip() words = word.split() if words == [] : continue if words[0] != 'From' : continue prin...
import pandas as pd """ How to read a tabular data file using pandas? """ orders = pd.read_table('http://bit.ly/chiporders') orders.head() movieusers = pd.read_table('http://bit.ly/movieusers', delimiter='|', names=['user_id', 'age', 'gender','occupation','zipcode']) print(movieusers.head())
import numpy as np ### 0s,1s, identical matrixes #Initialize all zero's(0s) matrix which default dtype='float64': zero_matrix = np.zeros((2,2)) print("Get 2d 0s matrix", zero_matrix) #Initialize all zero's(0s) matrix which default dtype='float64': one_matrix = np.ones((2,2)) print("Get 2d 1s matrix", one_matrix) #Ini...
#!/usr/bin/env python list_1 = [1, 1, 2, 3, 5, 8] # Problem 1 # Find last element of a list # solution 1 last_element = list_1[-1] print("The last element of the list is %i." % last_element) # solution 2 last_element2 = list_1[len(list_1) - 1] print("The last element of the list is %i." % last_element2) # solution...
#!/usr/bin/env python test = [{ 'name': 'Fabrizio', 'age': 32 }, { 'name': 'Adam', 'age': 13 }] # Filter print(filter(lambda x: x['age'] > 20, test)) # List comprehension print([x for x in test if x['age'] > 20]) # Iteration result = [] for x in test: if x['age'] > 20: result.append(x) pri...
#!/usr/bin/env python import random def initialise_field(width_local, height_local): """ Seed stage Initialises, e.g. populates, a field with a population of randomly selected alive (1) or dead (0) cells """ return [[random.randint(0, 1) for i in range(width_local)] for y in range(height_local...
#!/usr/bin/env python import math def sum(xs): """ Returns the sum of numbers contained in a list """ result = 0.0 for current_element in xs: result += current_element return result def average(xs): """ Returns the average of numbers contained in a list """ result...
#!/usr/bin/env python import csv # Step1 # Reads the data from the original file and prepares them for processing # 1.1 Reads line by line # 1.2 Extracts the 3 fields to be later processed # 1.3 Stores the fields/lines in memory original = "test.csv" # Opens the original csv file to transform with open(original, "r...
#!/usr/bin/env python import random import os import time def game_of_life(col, row): """ Returns the game of life """ field = initialise_field(col, row) print_field(field) while True: next_generation = compute_next_generation(field) os.system("clear") print_field(next_...
#!/usr/bin/env python # Exercise: generate a script that transform a list of nested lists into one list list1 = [[2, 4, 5], [12, 4, 7], [1, 4]] newlist = [] for current_element in list1: newlist.extend(current_element) print(newlist)
""" CSci 39542: Introduction to Data Science Program 2: Senator's Name Jiaming Zheng jiaming.zheng745@myhunter.cuny.edu Resources: https://www.geeksforgeeks.org/how-to-select-multiple-columns-in-a-pandas-dataframe/ """ import pandas as pd input_File = input("Enter input file name: ") output_File = input("Enter output...
print('with a for-loop') for i in range(1, 11): print('🧇' * i) print('with a while-loop') n = 1 while n < 11: print('🌯' * n) n += 1 print('with nested for- and while-loops') x = 1 z = '' for y in range(1, 11): while x <= y: z += '🥑' x += 1 print(z)
squares = { x**2 for x in range(10) } no_dupes_hello = { v.upper() for v in 'hello' } def are_all_vowels_in_string(string): return len( {char for char in string if char in 'aeiou'} ) == 5 print(squares) print(no_dupes_hello) print(are_all_vowels_in_string('hello')) print(are_all_vowels_in_string('aeiou')) print...
from car import Car, ElectricCar my_car = Car() #Class Car or my_car print my_car.engineSize #Engine size is public (ie has no __)and will be printed print my_car.getMake() #This will print if i add [def getMake(self): return self.__make] #print my_car.__make #Error message bc "make" is private (ie...
#!/usr/bin/python # Date : 31/12/2018 # Author : Syed Abdullah Jelani # Version : v.1 # Description :Hangman word game. import random import os import sys os.chdir("C:\\Users\\Syed Abdullah Jelani\\Desktop\\RGB to grayscale converter pics\\hangman") word_file = open("words.txt", "r") def parser(word...
from dataclasses import dataclass @dataclass class CacheNode: key: int = 0 val: int = 0 prev: 'CacheNode' = None next: 'CacheNode' = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.size = 0 self.cache = {} self.list = None ...
from collections import deque from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # empty tree class Solution: def find_height(self, root: TreeNode) -> int: ...
def gcd(a,b): if b==0: return a else: return gcd(b,a%b) class Rational(object): def __init__(self,p,q): self.p=p self.q=q def __add__(self,r): return Rational(self.p*r.q+self.q*r.p,self.q*r.q) def __sub__(self,r): return Rational(self.p*r.q-r.p*self.q,self.q*r.q) def __mul__(self,r): return Rational...
# -*-coding=utf-8 -*- #def move(n,a,b,c): # if n==1: # return a,'-->',c # move(n-1,a,c,b) # a,'-->',c # move(n-1,b,a,c) #print move(4,'A','B','C) #在交互模式下,return的结果会自动打印出来,而作为脚本单独运行时则需要print函数才能显示。 def move(n,a,b,c): if n==1: print a,'-->',c return move(n-1,a,c,b) print a,'-->',c move(n-1,b,a,c) move(2,'A','B...
# -*- coding=utf-9 -*- #比较函数的定义是,传入两个待比较的元素 x, y,如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0 def quene(x,y): if x.upper()<y.upper(): return -1 if x.upper()>y.upper(): return 1 return 0 print sorted(['bob', 'about', 'Zoo', 'Credit'],quene)
def average(*args): if len(args)==0: print 0 return sum=0.0 n=0 for elements in args: sum=sum+elements return sum/len(args) print average(1,2,3) print average(1,2) print average()
import statistics from math import ceil def histogram(dataset,height=8,width=80,full="X",empty="_"): """Given a list of data, draws an histogram of given width and height with given characters Returns if histogram was succesful""" mv = min(dataset) Mv = max(dataset) print("[",mv,":",Mv,"]") if(mv==Mv): print...
import random def word_to_guess(): list = ['banana','milan','prince','elite'] mysterious_word = random.randint(0,len(list)-1) return list[mysterious_word] def hint(mystery_word): if mystery_word == 'banana': return 'it is a famous fruit' elif mystery_word == 'milan': return 'it is ...
#https://www.bogotobogo.com/python/python_graph_data_structures.php #https://www.bogotobogo.com/python/python_Dijkstras_Shortest_Path_Algorithm.php # 1. The distance of the route A-B-C. # 2. The distance of the route A-D. # 3. The distance of the route A-D-C. # 4. The distance of the route A-E-B-C-D. # 5. The distance ...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- from lib.debugging import dprint from typing import NamedTuple class Row(object): """Table row with Cell objects.""" def __init__(self, cells=[]): self.cells = cells def addCell(self, cell): """Add a new cell to the table. Takes: cell (Cell)""" self.c...
from math import * def get_data(): answers = [("zero is", (4 - 4 + 4 - 4)), ("One is", (4 / 4 * 4 / 4)), ("Two is", (4 / 4 + 4 / 4)), ("three is", (4 - (4 / 4 / 4))), ("four is", ((4 - 4) / 4) + 4), ("five is", (((4 / 4) ** 4) + 4)), ...
import random print ("Choice ([34,56,89,12,5,7]:)", random.choice([34,56,89,12,5,7])) print("\n Shuffle() Method"); items = [45,2,5,23,78,9]; random.shuffle(items) print("Reshuffle the items: ",items); #============Randint=================== # randint()method for x in range(1 , 7): x = random.randint(1, 49) ...
# Design an algorithm that finds the maximum positive integer input by a user. # The user repeatedly inputs numbers until a negative value is entered. # Do not change this line max_int = 0 in_num = 0 while 1: in_num = num_int = int(input("Input a number: ")) if in_num > max_int: max_int = in...
"""VerticalHistogram""" def filter(word, counter): final_line = (' ', *word) list_for_print = {} for i in word: if i in list_for_print: list_for_print[i] += 1 else: list_for_print[i] = 1 print(list_for_print) filter([i if i.isalpha() else 0 for i in input()], 1)...
"""isPrime_large""" def prime(number):     """print prime number"""     if number > 2:         print(checker(number))     elif number == 2:         print("YES")     else:         print("NO")     def checker(number):     """check number is prime number?"""     for i in range(2, int(number**.5)+1):         if number%i ==...
"""almost mean""" def almost(dict_data, mean, amount, ref):     """find student that score almost mean"""       for i in range(amount):         data = input().split('\t')         dict_data[data[0]] = data[1]       for i in dict_data:         mean += float(dict_data[i])     mean /= amount       for i in dict_data:      ...
"""Create a notebook containing code from a script. Run as: python jupyter_from_py.py my_script.py """ import sys import nbformat from nbformat.v4 import new_notebook, new_code_cell, new_markdown_cell CELL_TYPE_UNKNOWN = 0 CELL_TYPE_CODE = 1 CELL_TYPE_MARKDOWN = 2 IDENTIFIER_CODE = '# In[ ]:' IDENTIFIER_MARKDOWN ...
class Square(object): def __init__(self, length,name): self._length = length self._name = name def display(self): print("length : ", self.length ) print("Name : ", self.name ) @property def length(self): return self._length @length...
# -*- coding: utf-8 -*- import math digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' def convert( num, baseOrig, baseDest ): result = '' num = toDecimal( num, baseOrig ) q = num while q > 0: r = q % baseDest q = q / baseDest result = digits[ r ] + result return result def toDecimal( num, base ): re...
# -*- coding: utf-8 -*- """ Spyder Editor This temporary script file is located here: /home/laubosslink/.spyder2/.temp.py """ # Variables myvar=5 myvar2=10 # Permutation myvar, myvar2 = myvar2, myvar # Affichage print("hello world".capitalize()); print("myvar=" + str(myvar) + " / myvar2=" + str(myvar2)) print("Hell...
#!/usr/local/bin/python3 import random; while True: try: minNumber = input('Podaj minimalna liczbe\n') maxNumber = input('Podaj maksymalna liczbe\n') ourNumber = random.randint(int(minNumber), int(maxNumber)) break except ValueError as error: print(error) finnished = Fa...
#NUMBER PALINDROME class Solution(object): def isPalindrome(self, num): str_num = str(num) original_index = 0 flag = None for index in reversed(range(len(str_num))): if str_num[original_index] == '-': return False elif str_num[original_inde...
''' for循环实现1~100求和 ''' sum=0 for x in range(101): sum+=x print(sum) #1~100偶数求和 sum=0 for x in range(2,101,2): sum+=x print(sum)
''' 比较运算符和逻辑运算符 ''' flag0=1==1 flag1=3>2 flag2=2<1 flag3=flag1 and flag2 flag4=flag1 or flag2 flag5=not(1!=2) print('flag0=',flag0) print('flag1=',flag1) print('flag2=',flag2) print('flag3=',flag3) print('flag4=',flag4) print('flag5=',flag5)
''' 通过键盘输入两个整数来实现对其算数运算 ''' a=int(input('a=')) b=int(input('b=')) print('%d+%d=%d'%(a,b,a+b)) # %d是整数的占位符 print('%d-%d=%d'%(a,b,a-b)) print('%d*%d=%d'%(a,b,a*b)) print('%d/%d=%d'%(a,b,a/b)) print('%d/%d=%f'%(a,b,a/b)) # %f是浮点数的占位符 print('%d//%d=%d'%(a,b,a//b)) print('%d%%%d=%d'%(a,b,a%b)) # %%代表%,由于%代表了占位符 print('%d**%...
rows, columns = [int(x) for x in input().split(', ')] matrix = [] for row in range(rows): matrix.append([int(x) for x in input().split()]) # for col in range(columns): # current_sum = 0 # for row in range(rows): # current_sum += matrix[row][col] # print(current_sum) columns_sum = [0] * columns...
from collections import deque bomb_effects = deque([int(x) for x in input().split(', ')]) bomb_casings = [int(x) for x in input().split(', ')] datura_bombs = 0 cherry_bombs = 0 smoke_decoy_bombs = 0 succeed = False while True: if datura_bombs >= 3 and cherry_bombs >= 3 and smoke_decoy_bombs >= 3: succee...
n = int(input()) matrix = [] for row in range(n): matrix.append([int(x) for x in input().split(', ')]) # flattening_matrix = [] # for row in matrix: # flattening_matrix.extend(row) # print(flattening_matrix) print([x for row in matrix for x in row])
import re text = input() pattern = r"\d+" matched_elements = [] while text: matches = re.findall(pattern, text) matched_elements.extend(matches) text = input() print(*matched_elements)
import csv import string import os import fnmatch import re from collections import Counter # This method checks each word of a list of words and removes some special characters def remove_punctuation(list_of_words): cleant_list_of_words = "" for word in list_of_words: # If char is not punctuation, ad...
import psycopg2 from datetime import datetime class DB: """Baseclass which provides functionality to query the a postgres databanks. Attributes: user (str) : db user. host(str) : db host. port(int) : db port. database(str) : db database. """ def __init__(self, user...
class Teacher(): def __init__(self,age,address): self.age = age self.address = address def information(self): print(self.age) print(self.address) Lijun = Teacher(45,'Beijing') Lijun.information()
class Statistics: def __init__(self): self.min = None self.max = None self.list=[] self.total = 0.0 self.n = 0 self.var = 0 def observe(self, x): if self.n > 1: delta = x - self.mean() self.list.append(x) self.list.s...
import hashlib hash1, salt1, fileName, fileText = "", "", "password_file.txt", "" lineCount = 0 def hash_with_sha256(str): hash_object = hashlib.sha256(str.encode('utf-8')) hex_dig = hash_object.hexdigest() return hex_dig def letsPlay(n): if n == lineCount: print("Job completed!")...
# 1. Пользователь вводит данные о количестве предприятий, их наименования # и прибыль за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия.. # Программа должна определить среднюю прибыль (за год для всех предприятий) # и вывести наименования предприятий, чья прибыль выше среднего и отдельно # вывести наименов...
# y = 2x - 10, если x > 0 # y = 0, если x = 0 # y = 2 * |x| - 1, если x < 0 # x - целое число x = int(input('x = ')) if x > 0: y = 2 * x - 10 elif x == 0: y = 0 else: y = 2 * abs(x) - 1 print(f'y = {y}') # Для ДЗ # import random # chr() # ord()
# 5. Вывести на экран коды и символы таблицы ASCII, начиная с символа # под номером 32 и заканчивая 127-м включительно. # Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке. # https://drive.google.com/file/d/1dRO7fXCLV1LLGWruoj_rnoHU5a8pRIjH/view?usp=sharing for i in range(32, 128): prin...
# 2. Написать программу сложения и умножения двух шестнадцатеричных чисел. # При этом каждое число представляется как массив, элементы которого это # цифры числа. Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] # и [‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’], # произведение...
n = int(input('До какого числа просеивать решето: ')) sieve = [i for i in range(n)] print(sieve) sieve[1] = 0 for i in range(2, n): if sieve[i] != 0: j = i + i while j < n: sieve[j] = 0 j += i print(sieve) result = [i for i in sieve if i != 0] print(result) ...
# 5. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят # и сколько между ними находится букв. print("Введите две строчных латинских буквы") first = input("Первая буква: ") second = input("Вторая буква: ") if first == second: n = ord(first) - ord('a') + 1 print(f"Введены одинаковые ...
''' Модуль, реализующий функционал работы ЭВМ Скорость измеряется в байтах в секунду Объём измеряется в мегабайтах Частота измеряется в герцах @author ADT ''' import time from typing import List, Optional, Dict, Any from collections import namedtuple from datetime import datetime from overrides import overrides from da...
# Projeto Orientação de objetos #Criar uma classe correntista com os seguintes atributos: #Nome do correntista; #Saldo em conta; #Histórico de saque e depositos #Deve possuir as seguintes capacidades: #Fazer deposito #Fazer saque #A classe dever ser iterável, a iteração deve ocorrer sobre o ...