text
stringlengths
37
1.41M
import networkx as nx import matplotlib-pyplot as plt g=nx.Graph() g.add_node(2) g.add_node(3) g.add_edge(2,3) g.add_edge(3,4) g.add_edge(4,6) g.add_edge(4,1) # print detrails of graph print(nx.info(g) # visualize Graph nx.draw(g) plt.show()
# -*- encoding: utf-8 -*- """ @File : 31-计算字符个数.py @Time : 2020/8/9 9:50 @Author : 李逍遥.Legend @Email : 1320474295@qq.com @Software: PyCharm @Target : """ ''' -----------票价规则---------- 轨道交通价格调整为: 6公里(含)内3元; 6公里至12公里(含)4元; 12公里至22公里(含)5元; 22公里至32公里(含)6元; 32公里以上部分,每增加1元可乘坐20公里。 ''' #...
# -*- encoding: utf-8 -*- """ @File : 16-while循环语句.py @Time : 2020/8/4 20:48 @Author : 李逍遥.Legend @Email : 1320474295@qq.com @Software: PyCharm @Target : """ import time a = 0 #while循环语句,当while条件一直符合时,会循环执行 while a < 1: money = int(input("请投币:")) if money >= 2: print("请上车……") time.s...
counta = 0 #前面的大写字母 countb = 0 #小写字母 countc = 0 #后面的大写字母 if str1[i].isupper(): if countb: countc += 1 else: counta += 1 countc = 0 if str1[i].isslower(): if counta != 3: counta = 0 countb = 0 countc = 0 else: if countb: counta = 0...
import random secret = random.randint(1,10) print("第一个作品") temp = input("输入你心中想的数字:") guess = 0 num = 1 while guess != secret and num < 3: num += 1 if temp.isdigit(): try: guess = int(temp) except (ValueError,EOFError,KeyboardInterrupt): print('输入错误') temp = inp...
from datetime import date from time import sleep cores = {'limpa':'\033[m', 'azul':'\033[34m', 'amarelo':'\033[33m' } #ETAPA 1 E 2 def obter_limite(): cargo = str(input('Qual cargo você ocupa na empresa que trabalha? ')) salario = input('Qual é o seu salário atual? R$') ...
d={1:"r",2:"p",3:"a",4:"r"} duplicate={} for key, value in d.items(): if value not in duplicate.values(): duplicate[key]=value print(duplicate)
n=int(input("enter a value:")) for i in range(n): print((str(n-i) + "*") * (n-1-i) + str(n-i)) for j in range(2,n+1): print((str(j) + "*") * (j-1) + str(j))
def gretestinteger(List): for i in range(size-1): List[i] = max(List[i+1:]) return List size=int(input("enter the size of the list:")) List = [] for i in range(size): List.append(int(input("enter the element number:"+str(i+1)+ "in the list"))) print("the list after replacing is:", gretestint...
f = open("day1.txt", "r") inputs = map(int, f.readlines()) total = 0 for i in inputs: module_fuel = 0 # total fuel for the module added_fuel = (i // 3) - 2 # added fuel for each iteration of the fuel calculation while added_fuel > 0: module_fuel += added_fuel added_fuel = (added_fuel // 3)...
''' This is the Machine Learning Project of Home Price Prediction it contain 13 labels and 1 feature that decides the predicted output For users go to the end of the programme and make changes in Using the model labels and get the predicted price by own .I attached housing.names and housing.data in files and by anal...
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ permutation = [] self.helper([], nums, permutation) return permutation def helper(self, array, remaining, permutation): if len(remaining) == 0:...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): m = {} def findFrequentTreeSum(self, root): """ :type root: TreeNode :rtype: List[int] ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int ...
def insert(root,node): if not root: root = node else: if node.val > root.val: if not root.right: root.right = node else: insert(root.right, node) else: if not root.left: root.left = node else:...
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ list = set(nums) result = [] for i in range(1, len(nums) + 1): if i not in list: result.append(i) return result...
# class Solution(object): # # def findDuplicates(self, nums): # """ # :type nums: List[int] # :rtype: List[int] # """ # list = set() # result = [] # for n in nums: # if n in list: # result.append(n) # else: # ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ list = []...
# Test objects used to test code # I made a few sample preloaded data structures to test the basic # functionality of some of my solutions class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class BinarySearchTree(object): ''' ...
# Definition for singly-linked list. # class ListNode(object): # # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ return self.helper(head, None)...
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ # hashmap for levels dic = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h'...
def removeDupNoExtraArray(dataSet): data = list(dataSet) startIndex = 0 lastIndex = len(data) - 1 lenOfData = len(data) while startIndex <= lastIndex: tempIndex = startIndex + 1 while tempIndex < lenOfData: if data[tempIndex] == data[startIndex]: print "\n======Match found======\nswap:1 ---",data[temp...
span = 2 if span == 1: print('Hello') elif span == 2: print('Howdy') else: print('Greetings') def func_with_no_args(): return f'Hello world! {span}' class someclass: def __init__(self, a): self.a = a def s(self): print(self.a) def convert_list_to_s...
"""Class Dog Description""" class Dog: def __init__(self, name, age): self.name = name self.age = age def sit(self): print(self.name.title() + " is now sitting") def roll_over(self): print(self.name.title() + " is now rolling over") class Car: def ...
""" Calculate Mahalanobis distance using Minimum Covariance Determinant ref) https://scikit-learn.org/stable/auto_examples/covariance/plot_mahalanobis_distances.html """ import numpy as np import matplotlib.pyplot as plt from sklearn.covariance import MinCovDet n_samples = 125 n_outliers = 25 n_features = 2 # genera...
expected_salary = 0 # Initialize a dictionary with a base salary value. expected_salaries = {"NY": 70000, "CA": 70000, "FL": 50000, "NC": 50000, "TX": 60000} # Initialize the user's info as an empty dictionary. user_profile = True def calculate_expected_salary_from_user_experience(user_information, user_trade_too...
from datetime import datetime from UserProfile1 import UserProfile, Developer, Designer print("Welcome candidate! Please enter in your information.") print() # Initialize the variables for the items that we will ask for the user to input. # They will default to False (or it could be None). # If the variable is n...
import os import re def walk_through_files(path, file_extensions): """ Generator function: searches the directory recursively to obtain all files that match the file_extensions Args: path: input path to search in file_extensions: Tuple of extensions to filter on """ for (dirpath, dirnames, filenames) in os...
import cv2 as cv import numpy as np img = cv.imread('Photos/cats.jpg') cv.imshow("Cats",img) blank = np.zeros(img.shape,dtype='uint8') cv.imshow("blank",blank) gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) cv.imshow('Gray',gray) # blur = cv.GaussianBlur(gray,(5,5),cv.BORDER_DEFAULT) # cv.imshow('Blur',blur) # canny ...
# print("Welcome to the rollercoaster!!") # height = int(input("What is your height? ")) # bill = 0 # if height >= 130: # print("You can ride he rollercoaster!") # age = int(input("What is your age? ")) # if age < 12: # bill = 5 # print("Please pay $5") # elif age <= 18: # bill ...
"""Code for combining columns to create new features. Giving velocities and accelerations are explained below.""" import datetime import dateutil from typing import Callable, Any import numpy as np import pandas as pd from tqdm import tqdm # Define constants used in the code below RANDOM_SEED = 888 ID_COUNT = 1000...
string = raw_input("Input here:") txt=string.split() result=[] for words in txt: if len(words) < 5: continue result.append(words) print ','.join(result),"has characters more than five letters"
def cipher( message: str, key: list[int], /, ): """ Encrypts message using row transposition cipher using supplied key. """ rows = len(message)//len(key) + (1 if len(message) % len(key) else 0) output = [] for row in range(rows): output.append(['']*len(key)) ...
#!/usr/bin/env python3 """ This script parses a file with the following format ID date-time string1 string2 string3 """ __author__ = "Cristian Garcia" __version__ = "0.1.0" __license__ = "MIT" import argparse import sys import re regex = r"^([0-9]+)\s+([0-9]{4}\-[0-1][1-9]-[0-3][0-9]-[0-2][0-9]:[0-6][0-9]:[0-6][0-9]...
myDict = {"name": "Anand", "age": "41", "countryOfBirth": "India", "favoriteLanguage": "Python"} def print_dictionary(x): print "My name is " + x["name"] print "My age is " + x["age"] print "I was born in " + x["countryOfBirth"] print "My favorite language is " + x["favoriteLanguage"] for item in...
from Product import Product class store(object): def __init__(self, products, location, owner): self.products = products self.location = location self.owner = owner def add_product(self, product): self.products.append(product) return self def remove_product(s...
from random import randrange class Board: """ The first two ranks of the board at start of a game of Fischer Random Chess. """ def __init__(self): def set_piece(max_skip_spaces, character): """ Put a piece onto the board. :param max_skip_spaces: The maximum n...
from board import Board from constants import * class Game: def __init__(self, player1, player2): self.board = Board() self.current_turn = 0 self.total_move_count = 0 self.human_player = player1 self.computer_player = player2 @property def current_player(self): ...
months = ['January','February','March','April','May','June','July','August','September', 'October','November','December'] month_abbvs = dict((m[:3].lower(), m) for m in months) def valid_month(month): if month: short_month = month[:3].lower() return month_abbvs.get(short_month) def valid_day(day): ...
def snake_to_camel(text): text = text.split('_') camel = text.pop() for chunk in text: camel += text.capitalize() def camel_to_snake(text): snake = '' for letter in text: if letter.isupper(): snake += '_' snake += letter.lower() return snake
from tkinter import * from tkinter import ttk # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame class VerticalScrolledFrame(Frame): """A pure Tkinter scrollable _mainFrame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable _mainFrame * Construct and pack/pl...
def opening_files(name): fav_foods = open(name) fav_foods_list = fav_foods.readlines() fav_foods.close() return fav_foods_list nina_fav_foods = opening_files("nina_fav_foods.txt") sara_fav_foods = opening_files("sara_fav_foods.txt") print nina_fav_foods, sara_fav_foods #if nina_fav_foods[0]==sara_fav_foods[0]: ...
#Class for applying the Luhn(Mod 10) Algorithm to generate or validate a check sum #Written by: D. Reilly 2012 class LuhnFormula: def doubleDigitAndSum(self,digit): #double a number, 0-9 and if it is >10 sum the resulting 2 digits dbl = int(digit)*2 if dbl > 9: str_dbl = str(dbl) new_val = int(str_dbl...
#!/usr/bin/env python # coding:utf8 class ChineseGetter(object): def __init__(self): self.trans = dict(dog="狗", cat="猫") def get(self, item): return self.trans.get(item, str(item)) class EnglishGetter(object): def get(self, item): return str(item) def get_localizer(language="E...
#!/usr/bin/env python # coding:utf8 from abc import abstractmethod, ABCMeta class AbstractProductA(metaclass=ABCMeta): @abstractmethod def productAOperation(self): pass class AbstractProductB(metaclass=ABCMeta): @abstractmethod def productBOperation(self): pass class Factory(metac...
#!/usr/bin/env python # coding:utf8 from abc import abstractmethod, ABCMeta class Product(metaclass=ABCMeta): @abstractmethod def productOperation(self): pass class Creator(object): __clazz = None def __init__(self, name): self.__clazz = name def creatorOperaton(self): ...
from base.Item import Item class Player: def __init__(self,name): """ Main player class, to store things like inventory and other things param name: The name of the player. Purely for astetics """ self.name = name self.health = 100 self.inventory = [] self.looking_at...
# -------------- #1) ##File path for the file file_path #Code starts here def read_file(path): #Opening of the file located in the path in 'read' mode file = open(path, 'r') #Reading of the first line of the file and storing it in a variable sentence = file.readline() #Clos...
# import the required modules import csv import mymod if __name__ == "__main__": file_name = input("Please enter the name of your file(including extension i.e. .csv .txt .xlsx). ") while True: try: elect_year = str(input("Please enter the election year.")) if int(elect_year) %...
import random class Die(): """docstring for Die class""" def __init__(self): """""" self.side = 0 def throw(self): """ This method is for throw dice""" self.side=random.randint(1,6) def get_value(self): """ This method is for getting value for dice thrown""" return self.side # is an Instance of cla...
a = [] list = [12,3,4,'anand',12,'raj'] # user_input = raw_input("Please Enter a value : ") for i in list: if len(a)>=1: if type(a[0]) == type(i): a.append(i) print "Value appended to List is : ", i else: print "This value is not typecast : ", i else: a.append(i) print "Initial Value appended to Li...
def get_problemkeys(filename): """ Takes in a dataset in XML format, parses it and returns a list with the values of tags with problematic characters. """ problemchars_list = [] for _, element in ET.iterparse(filename): if element.tag == 'tag': if problemchars.search(element.attr...
#!/usr/bin/python def funm(x): return x ** 2 def funf(x): return x > 2 and x < 5 def funr(x,y): return x + y l = [1,2,3,4,5] l1 = [6,7,8,9,0] print map(funm,l) print filter(funf,l) print reduce(funr,l) print zip(l,l1)
# First line take a number of country and if the country is repeating in list don't count that county and last give how many unique country are there # Example: # Line1: 7 # UK # China # USA # France # New Zealand # UK # France # Ans: 5 c=[] a = int(input()) for i in range(0,a): ele= str(input()) c.append(e...
a=float(1) e=0.5 while (a+e) != a: e=e/1.0001 print(e)
from functools import reduce class BoardWrapper: """ A hashable and __eq__ comparable representation of the board state. Exposes the Isolation board via the `board` attribute. Instances can be used as keys in a hash table. For example, use this class if you'd like to memoize the heuristic score ...
"""Create a Model class to hold quotes.""" class QuoteModel(): """Create a QuoteModel class to hold quotes.""" def __init__(self, body, author): """Store parameter values in local variable. Arguments: body {str} -- an inspiring quote. author {str} -- author of the quo...
#!/usr/bin/env python from sympy import * from sympy.utilities.solution import * x = Symbol("x") y = Symbol("y") z = Symbol("z") a = Symbol("a") eqs = [ [x - 3*y + z - 4, 2*x - 8*y + 8*z + 2, -6*x + 3*y - 15*z - 9], [x - 3*y + z - 4, 2*x - 8*y + 8*z + 2,], [x - 3*y + z - 4, 2*x - 8*y + 8*z + 2, 2*x - 8*...
# Second GA program import math import random from circle_class import Circle # import my circle class from tkinter import* # Problem found @ AI-junkie.com. This file uses a GA to find the largest circle that can fill a # space between other circles in the given grid. All that is necessary for the other circles # ar...
import math def make_int_array_from_string(string): string_array = string.split(" ") return [float(num) for num in string_array] def dot_multiply(row, column): result = 0 for i in range(len(row)): result += row[i] * column[i] return result def remove_column(matrix, column): answer_...
#asyncio2.py to build and run coroutines in parallel import asyncio import time async def say(delay, msg): await asyncio.sleep(delay) print(msg) async def main (): task1 = asyncio.create_task( say(1, 'Good')) task2 = asyncio.create_task( say(1, 'Morning')) print("Started at ", time.strftime("%X"))...
# myadd3.py is a class with with add two numbers method def add( x, y): """This function adds two numbers""" if (not isinstance(x, (int, float))) | \ (not isinstance(y, (int, float))): raise TypeError("only numbers are allowed") return x + y
# process1.py to create simple processes with function import os from multiprocessing import Process, current_process as cp from time import sleep def print_hello(): sleep(2) print("{}-{}: Hello".format(os.getpid(), cp().name)) def print_message(msg): sleep(1) print("{}-{}: {}".format(os.getpid(), cp...
# pandastrick4.py import pandas as pd weekly_data = {'day':['Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 'temp':[40, 33, 42, 31, 41, 40, 30], 'condition':['Sunny','Cloudy','Sunny','Rainy','Sunny', 'Cloudy','R...
# process5.py to use queue to exchange data from multiprocessing import Process from multiprocessing import Queue def copy_data (list, myqueue): for num in list: myqueue.put(num) def output(myqueue): while not myqueue.empty(): print(myqueue.get()) def main(): mylist = [2, 5, 7] myque...
#carexample7.py class Car: __mileage_units = "Mi" def __init__(self, col, mil): self.__color = col self.__mileage = mil def __str__(self): return f"car with color {self.color} and mileage {self.mileage}" @property def color(self): return self.__color @property ...
# thread3b.py when thread synchronization is used from threading import Lock, Thread as Thread def inc_with_lock (lock): global x for _ in range(1000000): lock.acquire() x+=1 lock.release() x = 0 mylock = Lock() # creating threads t1 = Thread(target=inc_with_lock , args=(mylock,), na...
#exception1.py try: #print (x) x = 5 y = 1 z = x /y print('x'+y) except NameError as e: print(e) except ZeroDivisionError: print("Division by 0 is not allowed") except Exception as e: print("An error occured") print(e)
#methodoverloading1.py class Car: def __init__(self, color, seats): self.i_color = color self.i_seat = seats def print_me(self, i='basic'): if(i =='basic'): print(f"This car is of color {self.i_color}") else: print(f"This car is of color {self.i_color} wi...
#iterator4.py class Week: def __init__(self): self.days = {1: 'Monday', 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday"} def __iter__(self): return WeekIterator(self.days) class WeekIterator: def __init__(self, ...
#test_mycalc_subtract.py test suite for substract class method import unittest from myunittest.src.mycalc.mycalc import MyCalc class MyCalcSubtractTestSuite(unittest.TestCase): def setUp(self): self.calc = MyCalc() def test_subtract(self): """ test case to validate two positive numbers""" ...
#asyncio1.py to build a basic coroutine import asyncio import time async def say(delay, msg): await asyncio.sleep(delay) print(msg) print("Started at ", time.strftime("%X")) asyncio.run(say(1,"Good")) asyncio.run(say(2, "Morning")) print("Stopped at ", time.strftime("%X"))
#iterator2.py class Week: def __init__(self): self.days = {1:'Monday', 2: "Tuesday", 3:"Wednesday", 4: "Thursday", 5:"Friday", 6:"Saturday", 7:"Sunday"} self._index = 1 def __iter__(self): self._index = 1 return self def __next__(se...
# mycalc.py with add,subtract, multiply and divide functions class MyCalc: def add(self, x, y): """This function adds two numbers""" return x + y def subtract(self, x, y): """This function subtracts two numbers""" return x - y def multiply(self, x, y): """This func...
import math def prime(n): func = lambda x: [x%i for i in range(2, int(math.sqrt(x)) + 1) if x%i ==0] return filter(func, range(2,n+1)) n = int(input("请输入一个比2大的数:")) print(list(prime(n)))
import re # import for regex expressions tokens = [] #output in array form user_input = input("Enter your input: ").split() #NB: Include spaces in your input for split function to work properly. print (user_input) for word in user_input: ...
#question1) écrire un algorithme power utilisant une boucle pour calculer x^n, x et n en entrée def power(x,n): valeur=1 for i in range(n): valeur=valeur*x # print(i,valeur) return(valeur) # print("##### power #####") # print(power(3,3)) #renvoit 27 # print(power(4,2)) #renvoit ...
#tours de Hanoi def deplacer(tour_de_dep , tour_arriv , disque): print("deplacer le disque " + str(disque) + " de la tour " + str(tour_de_dep) + " à la tour " + str(tour_arriv)) return # print(deplacer(2,3,5)) def hanoi(nombre_de_disque , tour_de_depart , tour_d_arrive): if nombre_de_disque < 1: ...
def fibonacci(N): U=[0]*N U[0]=1 U[1]=1 for i in range(2,N): U[i]=U[i-1]+U[i-2] return(print(U)) print(fibonacci(10))
Questions = [ { "body ": "Is this happening tomorow ?", "question_id": 1, "meetup_id": 1, "title": "Rehumanizing humans", "user": 1, "votes": 0 } ] user = 1 votes = 1 class QuestionsModel(): """ This class contains models for ques...
# this is similar to argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) def print_one(arg1): print "arg1:"+ %r % arg1 def print_none(): print "I've got nothin'." print_two("Zed","Shaw")...
list_of_strings = ["1", "9", "11", "100"] # Parse strings to integers list_of_integers = [int(item) for item in list_of_strings] # This one should be fine, we're providing a list of integers for item in list_of_integers: if item < 10: print(item) # This one will break, we're providing a list of strings, ...
def main(): aMatrix = [[0,1,0,0,1], [1,0,1,1,1],[0,1,0,1,0],[0,1,1,0,1],[1,1,0,1,0]] # for vertex in range(len(aMatrix)): # for edge in range(len(aMatrix[vertex])): # if aMatrix[vertex][edge] == 1: # print(vertex, ' Has Connection with ', edge) # print() print('...
def quickSort(nums): length = len(nums) return nums def main(): nums = [99, 44, 6, 2, 1, 5, 63, 0, 87, 283, 4, 0] print(quickSort(nums)) if __name__ == '__main__': main()
import pprint import requests def get_json_response(base): '''Gets data in JSON format for the exchange rates of common currencies compared to the base currency, which is taken as an argument(i.e base=USD). ''' url = 'https://api.fixer.io/latest?base={}'.format(base) json_response = reques...
from heapq import heappop, heapify class MyList(list): def __lt__(self, other): return self[0] < other[0] def merge_k_sorted_lists(arrs): """O(n*k*log(k))""" arr = [] heap = [] k = len(arrs) for i in range(k): heap.append(MyList([float('inf'), arrs[i].__iter__()])) for j...
"""Красно-черное дерево - бинарное дерево поиска, сбалансированное(h = O(log n) ~~ h <= 2log(n + 1)) 1. Каждый узел либо красный, либо черный 2. Корень и листья (NIL) - черные 3. У красного узла все дочерные узлы черные 4. Для каждого узла все простые пути от него до листьев, содержат одно и то же кол-во черный узл...
import random def main(): dirs=(0,0,0,0) entrance={'name':'Entrance Way','directions':dirs,'msg':'You are in Entrance Way'} liv...
# Power digit sum # Problem 16 # 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # # What is the sum of the digits of the number 21000? # # Again, a problem that is trivially implemented in Python thanks # to its handling of arbitrarily large integers: # # print("The sum of digits in 2^{0} is {1}".form...
# Special Pythagorean triplet # Problem 9 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. # # First, we recognize that i...
from abc import ABC, abstractmethod class Clothes(ABC): @abstractmethod def fabric(self): pass class Coat(Clothes): def __init__(self, V): self.V = V @property def fabric(self): return self.V / 6.5 + 0.5 class Suit(Clothes): def __init__(self, H): self.H = ...
class Cell: def __init__(self, cell_cell): self.cell_cell = cell_cell def __add__(self, other): if type(other) == Cell: return Cell(self.cell_cell + other.cell_cell) else: print('Error: Not the Cell type') def __sub__(self, other): if type(other) == ...
def generator(list_a, list_b): for i in range(0, len(list_a)): if i <= len(list_b) - 1: yield (list_a[i], list_b[i]) else: yield (list_a[i], None) tutors = ['Иван', 'Анастасия', 'Петр', 'Сергей', 'Дмитрий', 'Борис', 'Елена'] classes = ['9А', '7В', '9Б', '9В', '8Б'] # classes...
# creates random numbers/ matches, etc # import random # my_list=["Iram","Allyson","Dominique","Odie","Aidee","Oscar","Mom","Dad","Autumn","Marisa","Jr","Sinthia"] # for i in range(10): # x= random.choice(my_list) # print (x) import math print (math)
# while True: # line = input('> ') # if line == "done": # break # print (line) # print('Done') largest = None samllest = None try: while True: num = input("Enter a number: ") digit = int(num) if digit == "done": break except: print ("inval...
def max_name_len(firstname, lastname): print(f"The largest value of the length of my firstname and lastname is {max(len(firstname), len(lastname))}")
# If/ Else conditions are used to decide to do something based on something being true or false x = 40 y = 40 # Comparison operators (==, !=, >, <, >=, <=) - Use to compare values # Simple if if x == y: print(f'{x} is equal to {y}') # Simple If/ else if x > y: print (f'{x} is greater than {y}') else: pr...
res1 = int(input("Telefonou para a vítima? 1/Sim ou 0/Não: ")) res2 = int(input("Esteve no local do crime? 1/Sim ou 0/Não: ")) res3 = int(input("Mora perto da vítima? 1/Sim ou 0/Não: ")) res4 = int(input("Devia para a vítima? 1/Sim ou 0/Não: ")) res5 = int(input("Já trabalhou com a vítima? 1/Sim ou 0/Não: ")) ...
import random import string import re import argparse def num_to_string(number, digit_assign): for digit in digit_assign: number = number.replace(digit, digit_assign[digit]) return number # create testcases into 'into_file' file # max_testcase: numbers testcase # max_letter: maximum number of letter ...