text
stringlengths
37
1.41M
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: i=0 S=list(S) while i <len(S): if S[i]=='#' and i-1>=0: del S[i],S[i-1] i=i-2 elif S[i]=='#' and i==0: del S[i] i=i-1 ...
class Solution: def reverseOnlyLetters(self, S: str) -> str: S=list(S) current=[] pos=[] for i in range(len(S)): if (S[i]>="a" and S[i]<="z") or (S[i]>="A" and S[i]<="Z"): current.append(S[i]) pos.append(i) current=current[::-1] ...
class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if len(A)<=len(B): count=1 arr=A while len(arr)<=len(B)+2*len(A):# A="ab" B="bababa" size(A)*(n+2)头尾各多一次 if arr.find(B)!=-1: return count els...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head is None: return head old=head res=[] while old is not None: ...
class Solution: def reverse(self, x: int) -> int: if x>=0: A=list(str(x)) A=reversed(A) number=int("".join(A)) if number>=-pow(2,31) and number<=pow(2,31)-1: return number else: return 0 else: A...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #两个指针分别遍历左右,当节点相同时,遍历左右子树 class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root is None: return True def chec...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ i=0 while i < int(len(s)/2): temp=s[len(s)-i-1] s[len(s)-i-1]=s[i] s[i]=temp i=i+1
#Задача 5. #Відсортувати кожен рядок двовимірного масиву у порядку зростання. n = int(input("Enter number rows :")) m = int(input("Enter number cloums :")) num_lst = [] i=0 for i in range(n): num_lst.append([int(j) for j in input("Введите числа через пробел ").split()]) print(len(num_lst[i])) if len(num_lst[i]...
""" Keregessunk be pozitiv egesz szamokat addig, amig 0-t nem kapunk. Ezutan irjuk ki, hogy melyik szam hanyszor szerepelt, egeszen a legnagyobb kapott szamig. Pleda bemenet: -------------------------------------------- 1 1 2 1 5 0 -------------------------------------------- Pelda kimenet: -------------------------...
# -*- coding: utf-8 -*- from uiutil.tk_names import ttk from .base_widget import BaseWidget class Label(BaseWidget): WIDGET = ttk.Label STYLE = u"TLabel" VAR_TYPE = BaseWidget.string_var VAR_PARAM = u'textvariable' def __init__(self, *args, **kwargs): ""...
x = [7, 89, 54, 5, 6, 12, 32, 54, 78, 13, 46, 79, 123, 65] for i in range(0, 12): pos = i low = x[pos] for j in range(i+1, 13): if(low > x[j]): pos = j low = x[j] x[i], x[pos] = x[pos], x[i] print("Sorted Array :") for i in x: print(i, end=" ")
print("Loop Type 7") for i in range(1, 6): for j in range(1, i+1): print(i, end="") print() print("Loop Type 8") for i in range(1, 6): for j in range(1, i+1): print(j, end="") print() print("Loop Type 9") for i in range(1, 6): n = i for j in range(1, i+1): p...
# In tuple u cant modifyed the data # Used by () data = (10, 20, 30, -50, 30.40, "Life is Awseome") print(data) print(data[-1]) print(data[-2]) print(data[-3]) print(data[-4]) print(data[-5]) print(data[-6]) ############### print(data[0]) print(data[1]) print(data[2]) print(data[3]) print(data[4]) print(data[5])
# Type 1 a = 4 b = 5 total = (a*b) print(total) # Type 2 a = 9 b = 8 total = (a*b) print(total) # Type 3 a = 1245 b = 2568 total = (a*b) print(total) #Type 4 a = 123456 b = 980976 c = 132452 total = (a*b*c) print(total)
import random # Get the user's guess # Params: None # Returns: Integer # def get_guess(): # Get initial guess guess = raw_input('Enter your guess: ') # Assume it's not valid, until it's proven otherwise valid = False while valid != True: try: # Try and convert...
import copy import random # Consider using the modules imported above. class Hat: def __init__(self, **kwargs): self.contents = [] for key, value in kwargs.items(): counter = 0 while counter < value: self.contents.append(key) counter += 1 def draw(self, num_balls_to_draw): ...
# 선택정렬 # 최댓값을 찾아 맨 오른쪽값과 교체 # 버블정렬과 비슷하지만 이웃한 두 값을 정렬하는 과정이 없음 # 최댓값을 찾아야 하므로 정렬 상태에 관계없이 O(n^2) # 버블정렬보다 빠름 def sawp(x, i, j): x[i], x[j] = x[j], x[i] def selectionSort(x): for size in reversed(range(len(x))): print(len(x)-size, '번째') max_i = 0 ## 최댓값 찾기 for i i...
""" Este é o módulo nested.py, e fornece uma função chamada print_lol() que imprime listas que podem ou não estarem aninhadas """ """ Esta função requer um argumento posicional chamado "the_list" que é qualquer lista Python (de possiveis listas aninhadas). Cada item na lista fornecida é (recursivamente) impresso em ...
# This is a guess the number game. import random isPlaying = True while isPlaying: guessesTaken = 0 number = random.randint(1, 20) print('I am thinking of a number between 1 and 20.') isGuessing = True while isGuessing: print('Take a guess.') # There are four spaces in front of print. guess = input() guess...
#Description: Server side for TCP socket programming #Author: Coleman Hill #Date: September 28, 2021 import sys from socket import * #Creating the serverName or IP address serverName = "localhost" #Creating the port we will connect with serverPort = 12000 #Creating socket serverSocket = socket(AF_INET,SOCK_STREAM) #Ass...
def reverseString(input_string) : reverseString = input_string.split() print(reverseString) return ' '.join(reverseString[::-1]) if __name__ == '__main__' : input_string = 'i love programming very much' Output = reverseString(input_string) print(Output)
if '__name__' == '__main__' : print('hello') siglas = ['ES', 'MG', 'RJ', 'SP'] estados = ['São Paulo', 'Rio de Janeiro', 'Minas Gerais', 'Espírito Santo'] siglas_estados = {} for x, y in siglas, estados : siglas_estados[x] = estados print ('hello')
from gen_utils import * from plot_utils import * def reverse_segment_if_better(tour, i, j): """If reversing tour[i:j] would make the tour shorter, then do it.""" # Given tour [...A-B...C-D...], consider reversing B...C to get [...A-C...B-D...] A, B, C, D = tour[i-1], tour[i], tour[j-1], tour[j % len(tour)...
import os import sys list1 = ['banana', 'apple', 'mango'] list2 = ["orange", "papaya", "grapes"] list1.sort() # sort in ascending list2.sort() # sort in ascending list3 = list1+list2 #merge lists list3.sort() # default in ascending order print(list1) # sorted list print(list2) # sorted print(list3) ...
#!/usr/bin/python3 #import mysql python module import mysql.connector as mysql # function to connect to database and return handle # this function uses the global keyword to make the # database object and cursor global. def mysql_connect(host, user, password): global mydb global mycursor mydb = mysql.conne...
def bubble_sort(seq): """Inefficiently sort the mutable sequence (list) in place. seq MUST BE A MUTABLE SEQUENCE. As with list.sort() and random.shuffle this does NOT return """ changed = True while changed: changed = False for i in xrange(len(seq) - 1): if seq...
#Sacar los numeros primos de una lista dada y colocarlos en una lista nueva. def evaluar (lista): if isinstance (lista, list): return primolista(lista) else: return "Error, el valor introducido no es una lista" def primolista(lista): if lista == []: return [] elif pr...
def busqueda (num,lista): if isinstance (num, int) and (lista, list): return busqueda_aux (num, lista, len (lista) // 2) else: return "Error" def busqueda_aux (num, lista, indice): if indice == -1 or indice == len(lista): return False elif num == lista [indice]: ...
print("Hello world ") x=1 while x <20: print(x) x = x+1 print("see you ") def new_func(x): print(x+1)
import random environment = ["Dirty", "Clean"] perform = ["Cleaned", "Failed"] score = 0 numberOfSimulation = input("Enter number of time for simulation: ") i=0 while i < int(numberOfSimulation): print("Simulation:", i+1) state = random.choice(environment) if state == "Clean": score += 0 ...
class Solution: def findRelativeRanks(self, nums: List[int]) -> List[str]: s_nums= sorted(nums, reverse=True) output=[None]*len(nums) output[nums.index(s_nums[0])]="Gold Medal" if len(nums)>=2: output[nums.index(s_nums[1])]="Silver Medal" ...
import numpy as np class Solution: def isValidNine(self, arr): arr = [ number for number in arr if number != '.'] return len(arr) == len(set(arr)) def isValidSudoku(self, board: List[List[str]]) -> bool: board= np.array(board) for i in range(len(board)...
class Solution: def buddyStrings(self, A: str, B: str) -> bool: if A==B: return len(A)-len(set(A))>=1 elif set(A)==set(B) and len(A)==len(B): count=0 x=[] for i in range(len(A)): if A[i]!=B[i]: ...
# -*- coding: utf-8 -*- """Random test case generator. Randomly creates test cases for the stable matching problem presented in COMPSCI 320 Assignment 1. Assignment specification: https://canvas.auckland.ac.nz/courses/60521/assignments/235860 Usage: 1. put this file in the same directory/folder as yo...
def PrintAnimal(*animals): cat = "To jest kot" bat = "To jest nietoperz" bear = "To jest niedźwiedź" for animal in animals: if animal == 'bat': print(bat) elif animal == 'cat': print(cat) elif animal == 'bear': print(bear) else: ...
def double(x): return 2 *x def root(x): return x**2 def negative(x): return -x def div2(x): return x/2 number = 8 transformations = [double, root, div2, negative] tmp_return_value = number for transformation in transformations: tmp_return_value = transformation(tmp_return_value) print(tmp...
import random ''' min = 1 max = 6 dice = random.randint(min,max) print(dice) if dice == 1: print(" "," "," ") print(" "," o "," ") print(" "," "," ") elif dice == 2: print(" "," "," o") print(" "," "," ") print(" o "," "," ") elif dice == 3: print(" "," ...
class TVController(): def __init__(self, CHANNELS): self.CHANNELS=CHANNELS self.chan=0 def first_channel(self): self.chan=0 def last_channel(self): self.chan=len(self.CHANNELS)-1 def turn_channel(self,N) : self.chan=N-1 def ne...
# 3と5の倍数を生成 x = list(range(3,1000, 3)) y = list(range(5,1000, 5)) # 結合 x_y = x + y # 重複する値を除き、合計を算出 print(sum(set(x_y)))
n = int(input()) lst = list(range(1,n+1)) for num in lst: print(' ' * (n - num) + '*' * num)
# This is a simple calculator # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x ...
import unittest class TestMethods(unittest.TestCase): def setUp(self): self.s = Solution() def test1(self): self.assertTrue(self.s.judgeCircle('UD')) def test2(self): self.assertFalse(self.s.judgeCircle('UDRLRLRLU')) def test3(self): self.assertFalse(self.s.judgeCirc...
import unittest from main import * class TestMain(unittest.TestCase): def test_reverse_word(self): self.assertEqual(reverse_word('maison'), 'nosiam') self.assertEqual(type(reverse_word('maison')), str) def test_reverse_number(self): self.assertEqual(reverse_number(12), '-12') ...
num=int (input ("enter a number":)) if num>=0: if num==0: print ("zero") else: print ("positive") else: print ("negative")
#!/usr/bin/env python def max_from_left(values): max = 0 max_values = list() for i in values: if i > max: max = i max_values.append(max) return max_values def max_from_right(values): # pass max_from_left reversed values and reverse return reversed(max_from_left(r...
import numpy as np from numpy import loadtxt from keras.layers import Dense, Activation from keras.models import Sequential from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # Importing the dataset # load the dataset dataset = loadtxt('PipeDataset_1.csv', delimiter=',') # spl...
def flip_to_win(input): l = input.bit_length() marker = 1 current_count = 0 last_count = 0 seespace = False max_len = 0 for i in xrange(l): if input & marker != 0: current_count += 1 else: ll = last_count + 1 + current_count if max_len < ll: max_len = ll last_count ...
def powerSetHelper(inputL, marker): res = [] indx = 0 while marker > 0: if marker & 1 == 1: res.append(inputL[indx]) indx += 1 marker >>= 1 return res def powerset(inputL): allSets = [] for i in xrange(2**(len(inputL))): ss = powerSetHelper(inputL, i) allSets.append(ss) retu...
class Stack: def __init__(self): self._size = 0 self._data = [] def __str__(self): return ", ".join([str(i) for i in self._data]) + " size is " + str(self._size) def isEmpty(self): return self._size == 0 def push(self, data): if len(self._data) == self._size: self._data....
def palin_perm(input_str): count_dict = {} for s in input_str: if s == " ": continue elif s.lower() in count_dict: count_dict[s.lower()] += 1 else: count_dict[s.lower()] = 1 odd = False for s in count_dict: if count_dict[s] % 2 == 1: if odd: return False else: ...
__author__ = 'johnstivers' print("Welcome to Cross Product Calculator") VectorOne = input("Please enter the components of vector one, separated by commas.") VectorTwo = input("Please enter the components of vector two, separated by commas.") VectorOne = VectorOne.split(',') VectorTwo = VectorTwo.split(',') VectorOn...
#Fallout Hacking Game Challenge #Graeme Cliffe import random totalGuesses=4 def getWordList(wordLen,numWord):#returns randomized words from enable1.txt wordList=[] f=open("../enable1.txt","r") for line in f.readlines():#pull numWord words of wordLen length lineclean=line.strip("\n") if le...
# Write a function that extracts the even items in a given integer list, # named get_even_list, takes 1 parameter: l, where l is the given integer list ([1, 4, 5, -1, 10] for example), # returns a new list contains only even numbers ([4, 10] if the given list is [1,4,5,-1,10]) def get_even_list(l): lb = [] ...
from turtle import * speed(0) colors = ['red', 'blue', 'brown', 'yellow', 'grey'] color('red') begin_fill() for i in range(2): forward(50) left(90) forward(70) left(90) forward(50) end_fill() color('blue') begin_fill() for i in range(2): forward(50) left(90) forward(70) left(90) forw...
print('Answer the following algebra question: ') print('if x = 8, then what is the value of 4(x + 3)') data = { "1.": 35, "2.": 36, "3.": 40, "4.": 44 } for i in data: print(i, data[i]) nhap = int(input('Ur choice:')) dem = 0 if nhap == 4: dem += 1 print('Bingo') else: print(':(') print...
#### Control Flow #### # if, elif, else # Conditional statements are used to control the flow of the program # age = 14 # # if the user is over 15, allow them to buy a ticket # if age >= 15: # If this condition is met, the print statement will execute # print("Thank you, please proceed to your purchase.") # # # If ...
#manipulating list data ie., adding and deleting data ''' list=[1,2] print('list before append',list) list.append(3) print('list after append',list) list.extend([4,5,6,7,8]) print('list after extend',list) list1=["Harsh","Nisha"] list2=list+list1 print(list2) del list2[0:8] print('list after delete',list2) ...
list1=['Eglish','Hindi',1997,2000] list2=[11,22,33,44,55] list3=["a","b","c","d"] list4=[] print(list1[1]) print(list2[-2]) print(list3[-3]) for i in range(0,len(list2)): print(list2[i]) for i in range(0,len(list1)): print(list1[i]) list5=['H','A','R','S','H'] print(list5[0:3]) print(list5[3:]) pr...
import pygame as pg from .colors import WHITE, BLACK from .constants import WIDTH, HEIGHT, SQR_SIZE, COLS, ROWS from pictures.picture_import import CROWN class Piece(): def __init__(self, row, col, color): ''' position of the piece on the board and in the array, the color, the possible di...
def my_square(y): """squares a number using the ** operator """ return(y ** 2) def my_square2(x): """ uses the * operator""" return (x * x) print(my_square(42)) print(my_square2(42))
##FOR## meses=['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sept','Oct','Nov','Dic'] # for mes in meses: # if mes== 'Ago': # print('Es tu cumpleaños') # print(mes) # #para romper el ciclo # for mes in meses: # if mes== 'Ago': # break # print(mes) #para continuar el ciclo, sal...
import random class Weather: def isStormy(self, status = False): if status is False: status = random.choice([True, False]) return 'Stormy' if status == True else 'Sunny'
class Board: h_line = '\n--+---+--\n' v_line = ' | ' def __init__(self): self.cells = [ [' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' '] ] def draw(self): print(self.h_line.join([self.v_line.join(row) for row in self.cells])) def has_empty_cell(self): return self.empty_ce...
# -*- coding: utf-8 -*- """ Created on Wed May 27 17:30:00 2015 @author: papacheco """ num = input("Digite um numero:") n = range(10,1001,10) for p in n: if num == p: #print "SIM" res = "SIM" #print res break else: #print "Não" res = "NAO" #print res ...
import math import csv import xlwt from xlwt import Workbook # Workbook is created wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_sheet('Sheet 1') # pr int(math.cos(60*0.0174533)) # coordinates of chitkara rajpura lat1 = 30.518986 lat2 = 30.512601 lon1 = 76.655164 lon2 = 76.66357...
def list_multiply(list1, list2): for num1, num2 in zip(list1,list2): list3.append(num1*num2) #print(f"This is list 1: {list1}") #print(f"This is list 2: {list2}") print(f"This is list 3 (List that multiplys list1 and list2): {list3}") list1=[1,2,3,4,5,6] list...
#!/usr/bin/python3 def partition(array, low, max): """partition""" high = max pivot = array[max] low = low mid = low while mid <= high: if array[mid] < pivot: array[mid],array[low] = array[low], array[mid] low = low + 1 mid = mid + 1 ...
#!/usr/bin/env python # coding: utf-8 """ @author ChenDehua 2021/4/26 21:34 @note """ import time def consumer(cnt): gen = producer() next(gen) cnt = gen.send(cnt) while True: cnt -= 1 if cnt <= 0: print("consumer consumer , cnt = {}".format(cnt)) cnt = g...
import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() print(cancer.keys()) df = pd.DataFrame(cancer['data'],columns=cancer['feature_names']) print(df.head()) #scaling is necessary from sklearn.preproc...
class Solution: def bulbSwitch(self, n): """ :type n: int :rtype: int The idea is for every light bulb (index) in the list, we find out how many times the light bulb is been togglered (number of factor for this index). Then we determine if the light bulb is on or off. ...
# Project Bonus Question: Arrays names_array = ['Jordan', 'Debbie', 'John', 'Jenelle', 'Tony', 'Suzan', 'Tim','Alicia', 'Jordan', 'Jeff'] print("length of names_array is " + str(len(names_array))) print("instructors: ", names_array) searchForWho = input("Who are you searching for? ") for i in range(0, len(names_arra...
""" 作者:rainboysd 日期:2019年4月29日 功能:常用工具信息 版本:1.0 """ import random def createPosition(bounds): ''' 根据输入的界面元素边界,产生随机点击位置,主要集中在中心位置 获取元素中心点,然后从中心点,随机方向,随机距离增减 ''' bottom = bounds['bottom'] left = bounds['left'] right = bounds['right'] top = bounds['top'] ...
#! /usr/bin/env python # -*- coding: utf-8 -*- import logging from numbers import Number from decimal import Decimal ''' http://www.pythondiario.com/2013/05/ejercicios-en-python-parte-1.html 1- Definir una función max() que tome como argumento dos números y devuelva el mayor de ellos. (Es cierto que python tiene una ...
days = int(input("며칠?")) hours = days * 24 * 60 print ("일을 분으로 따지면", hours, "분이다.")
nil = [] def cons(x,xs) : return [x] + xs def head(xs) : return xs[0] def tail(xs) : return xs[1:] def null(xs) : return xs == nil def concat(xs,ys) : return xs + ys def snoc(xs,x) : return xs + [x] def concat(xs,ys) : return xs + ys def insert(x,ss) : def loop(ss,rs) :#x는 값안바뀌니 loop안에 ...
import random ############################################################################ #실습1 - 수독정답만들기 #1-1 정답 만들기 1단계 def create_board(): seed = [1,2,3,4] random.shuffle(seed) row0 = seed[:] row1 = seed[2:] + seed[:2] row2 = seed[1:2] + seed[0:1] + seed[3:4] + seed[2:3] row3 = seed[3:4] + s...
#Given an array of integers, return indices of the two numbers such that they add up to a specific target. Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1]. #space complexity O(1), time complexity O(n2) class Solution(object): def twoSum(self, nums, target): """ ...
''' Akshay Lavhagale Homework 04a - Develop with the Perspective of the Tester in mind ''' import requests import json def github_handle(userid): res = requests.get(f'https://api.github.com/users/{userid}/repos') # Executed if GitHub username is invalid if '"message":"Not Found"' in res.text: ...
class Building: def __init__ (self, name, capacity): self.name = name self.cap = capacity def get_info(self): print 'Building "' + self.name + '" can hold ' + str(self.cap) + ' people.'
print "Welcome to Palindrome Palace!" print "By royal decree, her highness Queen Hannah has declared that only palindromes may be allowed within the sacred walls of Palindrome Palace!" print "I am the royal guard, Noon!" print "What is thy name? For that will decide whether or not thou may enter these sacred walls!" pa...
import string from bs4 import BeautifulSoup import requests from fake_useragent import UserAgent import urllib from collections import Counter userloc='boston' #seperate into 2 functions, run the first, if we get a return then we find #distance and set a bool on whether or not they need travel/accomodation, #otherwi...
from loc_finder import search_web, possible_alternatives import string eventlist={'outside lands':'san francisco','lollapalooza':'chicago',\ 'statue of liberty':'new york city','world cup 2022':'doha',\ 'rio carnival':'rio de janeiro','Mardi gras':'new orleans',\ 'MaerzMusik':'Berlin','the louvre':'paris','oktoberfest ...
print("Select No. Operation") print(" 1 ADD ") print(" 2 SUBSTRACT ") print(" 3 MULTIPLY ") print(" 4 DIVIDE ") dict = {1:"ADD",2:"SUBSTRACT",3:"MULTIPLY",4:"DIVIDE"} user_input = int(input("Enter Operation number: ")) a = int(input("Enter a Numbe...
# Python Program to Put even and odd numbers in Separate List numlist = [1,2,3,4,5,6,7,8,9] even = [] odd = [] j = 0 while(j< len(numlist)): if(numlist[j] % 2 == 0): even.append(numlist[j]) else: odd.append(numlist[j]) j = j + 1 print("Element in even List is : ", even,"...
# Python program to find ASCII Values of Total Characters in a String str1 = input("Please Enter your Own String : ") for i in range(len(str1)): print("The ASCII Value of Character %c = %d" %(str1[i], ord(str1[i]))) ...
# -*- coding: utf-8 -*- """ Created on Thu Aug 6 22:40:30 2020 @author: Sujit Average Words Length eg "Hello world welcome to Python" """ sent = input("Enter your Sentence: ") sent_length = len(sent.split()) word_length = [len(word) for word in sent.split()] word_length average = sum(word_lengt...
""" CodinGame Sponsored Contest https://www.codingame.com/ide/puzzle/codingame-sponsored-contest Version: 0.4 Created: 04/07/2019 Last modified: 06/07/2019 """ import sys import math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. def n...
#simple snipped to reverse a string def reverse(text): rev = "" for i in text: rev = i + rev print(rev) return rev reverse("my word")
from .shape import Shape import turtle class Circle(Shape): def __init__(self, border, fill, heading, radius, coordinates=[]): super().__init__(border, fill, heading, coordinates) self.radius = radius def draw(self): super().draw() turtle.pendown() turtle.begin_fill() ...
def compare(a, b): if not (a.isdigit() and b.isdigit()): print("number must be integer") else: if int(a) > int(b): print(">") elif int(a) < int(b): print("<") else: print("=") first_digit = input("Enter first number\n") second_digit = input("...
class Book: def __init__(self, title, author=None, year=None): if author is None: author = '' if year is None: year = '' self.title = title self.author = author self.year = year def display(self): print(f"{self.title:<30}{self.author:<20}{...
from random import randint dragon = { 'hp': 2000, 'defence': 120, 'str': 150, 'weapon': 0 } hero = { 'hp': 1000, 'defence': 100, 'str': 120, 'weapon': 350, 'shield': 150 } def display_dragon_info(): print(f"Здоровье дракона: {dragon['hp']}hp") print("=" * 100) def modif...
import turtle turtle.color('red', 'yellow') turtle.begin_fill() for i in range(2): turtle.forward(100) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.end_fill() turtle.done() print(turtle.pos()) print(turtle.color())
from datetime import datetime current_date = datetime.now() print("Enter your name :") name = input().capitalize() print("Enter your last name :") last_name = input().capitalize() print("When were you born?") birth_date = int(input()) print("Where are you from?") location = input().capitalize() def age(birth_year):...
from Uno.Card import Card from Uno.Deck import Deck import random # shuffle deck if top card to play off of is a special card import sys solutions = [] def display(l): '''display the solution''' for item in l: print(item) def display2d(l): '''if no solution to dump all cards, display largest...
# 5. Пользователь вводит две буквы. Определить, на каких местах # алфавита они стоят, и сколько между ними находится букв. import string alphabet = list(string.ascii_lowercase) first_letter = input("Type a first letter: ") second_letter = input("Type a second letter: ") if len(first_letter) == 1 and len(second_lett...
# 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. import string alphabet = list(string.ascii_lowercase) pos_of_letter = input("Type the position of a letter in the english alphabet (from 1 to 26): ") if pos_of_letter.isdecimal(): pos_of_letter = int(pos_of_letter) if pos_of_lette...
class Solution: """ [1,2,3,4,5], [2,4,5,8,10], [3,5,7,9,11], [1,3,5,7,9] smallest one must in the first row, so try all ele in first rot from left to right, bisect on each row if idx == len(max), we find it """ def smallestCommonElement(self, mat: List[List[int]]) -> int: ...
class Solution: def largestRectangleArea(self, heights: List[int]) -> int: # brute force TLE # find the min height for every height # if len(heights) == 0: # return 0 # res = heights[0] # pt = 0 # def check(heights, end_idx): # res = m...
class Solution: """ Python中可以通过以"0b"或者"-0b"开头的字符串来表示二进制,如下所示 0b101 # 输出5 0b10 # 输出2 0b111 # 输出7 -0b101 # 输出-5 """ def encode(self, num: int) -> str: # bin return the binary format number return bin(num + 1)[3:]