text
stringlengths
37
1.41M
def string_before(str1, str2, case_sensitive = True): s1=str1 s2=str2 if case_sensitive == True: s1 = str1 s2 = str2 else: s1=str1.lower() s2=str2.lower() if s2 in s1: i=s1.find(s2) S=str1[:i] else: S = '' return S def string_after(s...
i = 1 while i <= 10: print(i) i = i + 1 websites = ["facebook.com", "google.com", "amazon.com"] for site in websites: print(site) for i in range(5): print(i)
import unittest import math from vector3dm import Vector3dm class TestVector3dm(unittest.TestCase): # tests from https://www.math.utah.edu/lectures/math2210/9PostNotes.pdf def test_convert_to_cartesian(self): r = 8 theta = math.pi/4 phi = math.pi/6 v = Vector3dm(r,theta,phi,"s") # the expected answe...
'''coleccion= {1:"Frank",2:"Jose",3:"Maria",4:"Thomas",5:"Javier"} for clave,valor in coleccion.items(): print(f"EElemento :{clave}->{valor}")''' coleccion= "Frank" for i in coleccion: print(f"{i}",end=".")
'''print("Tienen dos elementos ,clave y valor") diccionario={ "azul":"blue", "rojo": "red","verde":"green"} diccionario["amarillo"]="yellow" diccionario["azul"]="BLUE" del(diccionario["verde"]) print(diccionario)''' equipo = {10:"Paulo Dybala",11:"Douglas Costa", 7:"Cristiano Ronaldo"} print(equipo.get(6,"No existe un ...
print("No existen pero se simulan en python") pila =[1,2,3] #aGREGANDO ELEMENTOS POR EL FINALDE LA PILA pila.append(4) pila.append(5) print(pila) #Eliminar elemetos del final de la "pila" n=pila.pop() print("Sacando el elemento",n) print(pila)
a=5 b=10 a,b=b,a print(f"El valor de A es:{a} y de B es:{b}")
# sales by match # https://www.hackerrank.com/challenges/sock-merchant/problem def sock_merchant(socks: list[int]) -> int: """Determine how many pairs of socks with matching colors. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there...
# find digits # https://www.hackerrank.com/challenges/find-digits/problem def find_digits(n: int) -> int: """Count the number of divisors for each digit that makes up the integer. Args: n (int): value to analyze Returns: int: number of digits in `n` that are divisors of `n` """ r...
# number line jumps # https://www.hackerrank.com/challenges/kangaroo/problem def kangaroo(x1: int, v1: int, x2: int, v2: int) -> str: """Determine if two kangaroos will meet Args: x1 (int): kangaroo 1 starting position v1 (int): kangaroo 1 jumping distance x2 (int): kangaroo 2 star...
# staircase # https://www.hackerrank.com/challenges/staircase/problem def staircase(n: int): for i in range(1, n + 1): print(" " * (n - i) + "#" * i)
# electronics shop # https://www.hackerrank.com/challenges/electronics-shop/problem def get_money_spent(keyboards: list[int], drives: list[int], budget: int) -> int: """Find the cost to buy the most expensive computer keyboard and USB drive that can be purchased with a given budget Args: keyboards (li...
# designer pdf viewer # https://www.hackerrank.com/challenges/designer-pdf-viewer/problem def designer_pdf_viewer(heights: list[int], word: str) -> int: """Determine the area of the highlighted word. Args: heights (list[int]): the heights of each letter word (str): string Returns: ...
from NeuralNetwork import NeuralNetwork import pandas as pd # Data 1 print('Starting training data 1') data = pd.read_csv('dataset.csv').values N, d = data.shape X = data[:, 0:d - 1].reshape(-1, d - 1) y = data[:, 2].reshape(-1, 1) p = NeuralNetwork([X.shape[1], 5, 1], 0.1) p.fit(X, y, 10000, 100) # This will print the...
# 开发者:Lingyu # 开发时间:2020/12/26 9:56 # Location:C:\Users\admin\anaconda3\envs\Numpy # Conda executable:C:\Users\admin\anaconda3\Scripts\conda.exe # 创建数组,得到ndarray的数据类型 from random import random import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, ]) b = np.array(range(1, 8)) c = np.arange(1, 8) # a, b,...
from unittest import TestCase from controller.command_interpreter import Controller from model.toy_robot import Robot # Tests the Robot Model class RobotModelTest(TestCase): # Validates that the robot object is created with no parameters def test_create_empty_robot(self): robot = Robot() sel...
numero_1=int(input("Entre com um número: ")) numero_2=int(input("Entre com outro número: ")) numeros = [5,2,3,1] print("Conjunto de números: ", numeros) print("\nUsando / para divisão: ",numero_1/numero_2) print("\nUsando // para divisão: ",numero_1//numero_2) print("\nUsando % para divisão: ",numero_1%numero_2) prin...
numero = int(input("Digite o número \n--> ")) cont = numero+10 while(numero < cont): numero+=1 print(numero)
produto = float(input("Digite o valor do produto: R$")) if(produto < 20): print("O lucro será de 45%, o valor de venda do produto é de: R${}".format(produto*0.45 + produto)) elif(produto >= 20): print("O lucro será de 30%, o valor de venda do produto é de: R${}".format(produto*0.30 + produto))
import stack_class topA = stack_class.stack_class() topB = stack_class.stack_class() topC = stack_class.stack_class() def move(A,B): if B.empty(): B.push(A.top()) A.pop() else: if A.top() > B.top(): print("이동이 불가능합니다.") return 0 else: ...
# coding: utf-8 # In[ ]: # 반복문 fun # In[ ]: def add(a,b): return a+b; #f리턴이 없는 함수는, 프로시져 => 전역변수를 이용해서 값 변경하는 경우에 많이 사용됨 #프로시저는 변수에 값을 할당하면 안됨. # In[ ]: #namespace #local 지역변수 #global 전역변수 #상수와 비슷한 느낌.. #지역변수에서 전역변수값을 바꾸고 싶을 때는, global a , a = 3 a =3 def add(a,b): global a = 2; return a+b; ...
# coding: utf-8 # In[1]: #self object만의 값 # In[3]: class Person: # class Person의 멤버변수 name = "홍길동" number = "01077499954" age = "20" # class Person의 메소드 def info(self): print("제 이름은 " + self.name + "입니다.") print("제 번호는 " + self.number + "입니다.") print("제 나이는 " + se...
#---------- # Devin Suy #---------- from Algorithm.GameState import GameState # Human player optimizes for minimal score # Bot optimizes for maximum score class MiniMax: def __init__(self, game_states): self.game_states = game_states self.initial_state = game_states[-1] ...
""" Triangle Classification @author: Sanjeev Rajasekaran """ import unittest def classifyTriangle(a, b, c): """ takes three sides of the triangle as input """ if a+b < c or a+c < b or b+c < a: return "Not a Triangle" RightTriangle = "Not Right Triangle" if (pow(a, 2) + pow(b, 2) ==...
from turtle import * class Ball(Turtle): def __init__(self,x,y,dx,dy,r,color): Turtle.__init__(self) self.pu() self.x=x self.goto(x,y) self.y=y self.dx=dx self.dy=dy self.r=r self.shape("circle") self.color(color) self.shapesi...
import csv from array import array from collections import defaultdict # def main(f, col=0): # return get_file_max(f, col) def get_file_max(f, col): """ gets the row with the maximum value at column col in file f """ with open(f) as csv_file: csv_reader = csv.reader(csv_file) next(...
import sys import pygame from settings import Settings from paddle import Paddle from paddle_ai import PaddleAI from ball import Ball from scoreboard import Scoreboard class Pong: """Overall class managing game assets and behavior.""" def __init__(self): """Initialize the game and crea...
a=int(input("Enter the A value")); b=int(input("Enter the b")); c=int(input("Enter the C")); if(a==b==c): print(a," The Entered Three values are Equel"); elif(a==b>c): print("A and B is equel and biggest"); elif(a<b==c): print("B and C is equel and biggest"); elif(a==c>b): print("A and C is equel an...
t=(1,2,3,4,3,5,3,7,8); print("The tuple is ",t); s=str(t); print("The converted string from the tuple is ",s); l=list(t); print("The converted list from the tuple is ",l); length=len(t); print("The 4th length in tuple is ",t[3]); print("The 4th length in tuple from the last is ",t[length-4]); print("The repeated elemen...
def abcd(a): l=sorted(a) b=[] for i in a: b.append(i) if(b==ls): return True else: return False s=input("Enter the word to check whether it is alpabatical order"); if(abcd(s)): print("It is in alpabatical order"); else: print("It is not in alpabatical ord...
p=float(input("Enter the Principle Amount")); r=float(input("Enter the Interst Rate")); n=int(input("Enter the Time value")); print("The Compunt Interest Value is ",(p*n*r)/100);
class upper: def __init__(self,s): self.s=s; def print_string(self): print(self.s.upper()); s=input("Enter the string to be printed in upper case"); u=upper(s); u.print_string();
class Solution(object): def wordBreak(self, s, wordDict): sz = len(s) dp = [False for _ in range(sz)] for i in range(sz): for word in wordDict: if not cmp(word,s[i-len(word)+1:i+1]) and (i==len(word)-1 or dp[i-len(word)]): dp[i] = True return dp[-1] s = 'leetcodeleet' wordDict = set(['leet','code'...
import sys class ListNode(object): def __init__(self,x=sys.maxint): self.val = x self.next = None def printList(head): while head: print head.val, ' ', head = head.next print class Solution(object): def mergeKLists(self, lists): def divideLists(s,e): if s > e: return None elif s == e: return ...
from collections import defaultdict class Solution(object): def wordBreak(self, s, wordDict): d = {len(s):['']} def parse(i): if i not in d: d[i] = [s[i:j] + (word and ' ' + word) for j in range(i+1, len(s)+1) if s[i:j] in wordDict for word in parse(j)] return d[i] return parse(0) s...
#!python3 #coding: utf-8 import fileinput input_obj = fileinput.input() for data in input_obj: A, B = data.strip().split() print(int(A.find(B) >= 0))
import sqlite3 connect = sqlite3.connect('college.db') cursor = connect.cursor() query="select*from studentDetails" cursor.execute(query) for rows in cursor.fetchall(): print(rows[1],rows[2]) cursor.close() connect.close()
import math, logging from Error_info import * from Log import LogConfig class Cal(BuildError): @classmethod def __init__(self): logging.info("Start") # 正方形面积 def Square_Area(self, length): try: if length < 0: raise PositiveIntegerError ...
citizen = input("Are you a U.S. citizen (or born in Puerto Rico, Guam, or U.S. Virgin Islands)? ") if citizen[0].lower() == "n": print(" You are ineligible to vote in NY.") if citizen[0].lower() == "y": age= input("Are you at least 18 years of age? ") if age[0].lower() =="n": print(" You are ineligible to v...
class Car(): """Object """ def __init__(self): self.model = None self.tires = None self.engine = None def __str__(self): return '{} | {} | {}'.format(self.model, self.engine, self.tires) class Director: def __init__(self, builder): self._builder = builder ...
N=float(input('Enter the N value : ')) if N>=0: print('The entered value',N,'is an positive number') else: print('The entered value',N,'is an not a positive number')
import asyncio import asyncpg from datetime import date async def main(): # conn = await asyncpg.connect( # user='admin1', password='12345678', # database='demo1', host='127.0.0.1' # ) conn = await asyncpg.connect( "postgresql://admin1:12345678@localhost/demo1" ) ...
from collections import namedtuple from dataclasses import dataclass @dataclass(frozen=False) #если Ложь, можем менять объекты class User: id: int username: str is_staff: bool= False u = User(id=1, username='john') admin = User(id=42, username='admin', is_staff=True) print("user", u) print("admin", admin...
import csv def read_csv_cars(): with open('cars.csv') as f: csv_reader = csv.reader(f, delimiter=',') lines_count = 0 print("csv_reader:", csv_reader) for row in csv_reader: # print(repr(row)) if lines_count == 0: print("Columns:", " | ".join(r...
# # @lc app=leetcode id=557 lang=python3 # # [557] Reverse Words in a String III # # @lc code=start class Solution: def reverseWords(self, s: str) -> str: new = "" split = s.split() # split the words split_list_reversed = split[::-1] # print(split_list_reversed) split_stri...
# Programmed by Kevin Wallace # Bioinformatics Assignment 1 part 3 # This program gives you the complimentary DNA strand for a given DNA sequence # and prints both for the user DNASequence = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT" #change to lowercase to prevent re replacing what you already chang...
##################################################### # No code change allowed ##################################################### import math import random as rnd class Stop: def __init__(self, x, y): self.x = x self.y = y @property def get_id(self): return str(self.x) + "-" +...
def print_max(a,b): if a > b: print(a," is maximun") elif a == b: print(a," is equal to ", b) else: print(a," is minimun") print_max(3,4) x = 5 y = 5 print_max(x,y) x = 7 y = 2 print_max(x,y)
import math import itertools num1 = input('enter number 1\n') num2 = input('enter number 2\n') num3 = input('enter number 3\n') num4 = input('enter number 4\n') numbers = [int(num1), int(num2), int(num3), int(num4)] # solution is a brute-force method computing possible permutations, taken from LeetCode class solut...
import collections import numpy as np import pandas as pd import re from patsy import dmatrices def movies(filepath): ''' Converts raw data in movies.dat download file (of form "<MovieID><Title><MoviePopularity>", as noted in Tag Genome README) to pandas DataFrame. Separates movie title and relea...
""" Build graph of substrings of texts For every word: 1) word S=s1s2..sn-1sn creates n-2 words of length 3: w1 = s1s2s3, w2 = s2s3s4, w3 = s3s4s5, wn-2 = sn-2sn-1sn 2) if word wi is not in graph, it will create 3) for every pair of words (wi, wi+1) add oriented edge of weight = 1, or increase the weight by 1 """ from ...
def sucesionFibonacci(n): f0 = 0 f1 = 1 fibonacci=[f0,f1] for numeros in range(n): aux = f0 + f1 fibonacci.append(aux) f0 = f1 f1 = aux def sucesionPadovan(n): sucesion = [] for i in range(n): if i == 0 or i == 1 or i == 2: ...
#Crea una funcion que simule el juego de Piedra, papel o Tijeras def Piedra_Papel_Tijeras(): jugador1 = input("Jugador 1, ¿Cuál es tu elección?") jugador2 = input("Jugador 2, ¿Cuál es tu eleccion?") if jugador1 != jugador2: if(jugador1 == "piedra" and jugador2 == "tijeras") or (jugador1 == "...
#crea una funcion que dada una secuencia de numeros devuelva la suma de todos los elementos def Devuelve_Suma(lista): return sum(lista) lista = [2,4,4,5] print(Devuelve_Suma(lista))
#!/usr/bin/env python # -*- coding: utf-8 -*- # Ctf.pediy.com ctf2017 crackme 2 keygen # python 3.6.0 32bit # written by ٺ # 2017/06/14 import time def main(): start_time = time.clock() for sn in range(11111111,100000000): if check_input(sn) == 1: if check_answer(sn,calchash...
#For the following practice question you will need to write code in Python in the workspace below. This will allow you to practice the concepts discussed in the Scripting lesson, such as reading and writing files. You will see some older concepts too, but again, we have them there to review and reinforce your understan...
#Multiples of Three #Use a list comprehension to create a list multiples_3 containing the first 20 multiples of 3. multiples_3 = [num * 3 for num in range(1,21)]# write your list comprehension here print(multiples_3)
#Write a function named readable_timedelta. The function should take one argument, an integer days, and return a string that says how many weeks and days that is. For example, calling the function and printing the result like this: #print(readable_timedelta(10)) #should output the following: #1 week(s) and 3 day(s)....
#Create a numpy array of strings containing letters 'a' through 'j' (inclusive) of the alphabet. Then, use numpy array attributes to print the following information about this array: #dtype of array #shape of array #size of array #The code you submit in the code editor below will not be graded. Use the results from ...
#Write a for loop that iterates over the names list to create a usernames list. To create a username for each name, make everything lowercase and replace spaces with underscores. Running your for loop over the list: #names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"] #should create #usern...
#Factorials with For Loops #Now use a for loop to find the factorial! #It will now be great practice for you to try to revise the code you wrote above to find the factorial of a number, but this time, using a for loop. Try it in the code editor below! # number to find the factorial of number = 6 # start with our ...
# l = ['magical unicorns',19,'hello',98.98,'world'] # # def typelist(x): # newlist=[] # # for i in range (0, len(x)): # # print "The array you entered is integer type" # print "Sum:", sum(x) # # # typelist([1,2,38,6, "charlie"]) def typeList(x): # Useage of Int and Str here is great. Con...
#Multiples #Part 1 for odds in range (1,1000,2): print odds #Part 2 x = 5 while x < 1000005: print x x = x + 5 #Sum list & Average List a = [1, 2, 5, 10, 255, 3] b = sum(a) / len(a) print sum(a) print b
for e in range (0,10): if e % 2 == 0: print("*" + " " + "*" + " " + "*" + " " + "*" + " " + "*") else: print (" " + "*" + " " + "*" + " " + "*" + " " + "*" + " "+ "*") tupl = (2,99,0,5,5) print tuple(enumerate(tupl)) capitals = {} #create an empty dictionary then add values capitals["svk"] = ...
# # counter = 0 # x = [1,2,5,6,5,16] # y = [1,2,5,6,5,16] # # for i in range (0, len(x)): # if x[i] == y[i]: # counter = counter + 1 # if counter == len(y): # print "The lists are the same" # else: # print "The lists are different" # ############################################################# # C...
import unittest class Histogram: def draw(self,size): return '*'*size def draw_list(self,sizes): histogram = [] for size in sizes: row = self.draw(size) histogram.append(row) return histogram class Test_Histogram(unittest.TestC...
import sys """ 파괴되지 않은 건물 https://programmers.co.kr/learn/courses/30/lessons/92344?language=python3 """ def solution(board, skill): answer = 0 R, C = len(board), len(board[0]) mat = [[0] * (C + 1) for _ in range(R + 1)] for s in skill: type, r1, c1, r2, c2, degree = map(int, s) if ty...
import requests # getting user input for link print("Enter Url to be shortened") url = input() # hiding my api key use provided executable file for testing api_key = "my api key" # using cuttly api with key and given url to make shortened link api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}" ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def solve(a, b, c): return tuple([(a*i+b)%c for i in range(6)]) == (0, 4, 2, 5, 3, 1) def go(): for c in range(1, 20000): print(c) for a in range(0, c): for b in range(0, c): if solve(a, b, c): prin...
def add(a,b): return a+b def evenList(a): l=[] for i in range(1,a): if i%2==0: l.append(i) return l
# -*- coding: utf-8 -*- skritoStevilo = 8 vnos = 0 konec = False nadaljevanje = True budget = int(raw_input("Vnesi koliko denarja želš porabiti. Za vsako igro avtomat pobere 1\xe2\x82\xac: ")) while budget != 0 and konec != True: while (vnos != skritoStevilo and konec != True): budget = budget - 1 v...
import pdftotext # Load your PDF with open("Untitled.pdf", "rb") as f: pdf = pdftotext.PDF(f) # # If it's password-protected # with open("secure.pdf", "rb") as f: # pdf = pdftotext.PDF(f, "secret") # How many pages? print(len(pdf)) # Iterate over all the pages for page in pdf: print(page)
def print_progress(cur, tol, _l=20): """ 小工具打印进度 cur 现在进行了多少 tol 一共有多少 _l 进度条长度默认20 使用: if __name__ == '__main__': lis = range(777) for i in lis: print_progress(i, len(lis)) time.sleep(0.01) print_progress(1, 1) ...
#! /usr/bin/env python2 def robot_move(moves): moves = [('N', 2), ('E',4), ('S', 1), ('W', 3)] x = 0 y = 0 for move in moves: if move[0] == "N": y = y + move[1] if move[0] == "S": y = y - move[1] if move[0] == "E": x = x + move[1] if...
def sum_of_divisible_naturals(limit): total = 0 for n in range(1, limit): if n % 3 == 0 or n % 5 == 0: total = total + n return total if __name__ == '__main__': print(sum_of_divisible_naturals(1000))
def sort(l): if len(l) > 1: mid = len(l) // 2 left_list = l[:mid] right_list = l[mid:] sort(left_list) sort(right_list) i, j, k = 0, 0, 0 while i < len(left_list) and j < len(right_list): if left_list[i] <= right_list[j]: l[k] = l...
import math import random from lib_randomgraph import RandomGraph from lib_heap import Heap def main(): graph = RandomGraph('Gnp', 20, edge_spec=.5) print(graph) budget = 40 nodes, value = spanning_tree(graph, budget) print('selected nodes ', nodes) print('total value ', value) def prim_M...
import csv import time import sys import math from datetime import time def get_csv(): with open("data.csv", 'r') as csvfile: # opening reader reader = csv.reader(csvfile, delimiter = ',') # read into list data = [] for row in reader: data.append(row) # ...
class Bodybuilder: """ This builds a bodybuilder class. A bodybuilder has a name, weighs certain amount of pounds ,and attends a certain gym. """ def __init__(self, name, weight, gym): self.name = name self.weight = weight self.gym = gym # a bodybuild...
from random import randint class tickets(): def __init__(self): self.holders ={} def Purchase_ticket (self,Name,Category): self.ticket_num =randint(10000,99999) self.Name= Name if Category=="1": print("You have to pay $100 for VIP") self.price=100 ...
def team_olympiad(): n = int(input()) members = [int(x) for x in input().split(' ')] programming = [] maths = [] pe = [] for i, member in enumerate(members): if member == 1: programming.append(i + 1) if member == 2: maths.append(i + 1) if member ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root: TreeNode, min_depth=0) -> int: if not root: return 0 queue = [] queue.append(root) ...
import collections class HashSolution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False char_hash = {} for char in s: if char not in char_hash: char_hash[char] = 1 else: char_hash[char] += 1...
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def insertNewNode(self, head: TreeNode, newNode: TreeNode): if newNode.val < head.val: if head.left: ...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def __init__(self): self.nodes = [] def swapTailWithNext(self, current: ListNode, oddNext: ListNode, oddTail: ListNode): next_of_curre...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.diameter = 0 def diameterOfBinaryTree(self, root: TreeNode, is_root=True) -> int: if not root: return 0 if is_root: ...
# Find a sequence of transpositions of letters that transform # the sequence MARINE (letters are numbered 0..5) to the sequence AIRMEN. # Transpositions are represented by pairs of integers. For example, the pair (0,1) transforms MARINE to AMRINE. # Transpositions are performed from left to right. # You should define t...
import re def hey(phrase): stripped = phrase.strip() if not stripped: return "Fine. Be that way!" question = __is_question(stripped) shouting = __is_shouting(stripped) if question and shouting: return "Calm down, I know what I'm doing!" elif question: return "Sure." ...
import math class Shape: def area(self): pass def perimeter(self): pass class Square(Shape): def __init__(self, length = 0): self.length = length def area(self): return self.length ** 2 def perimeter(self): return self.length * 4 d...
class Chat: chat_room = [] robot_text = '' human_text = '' counter = 0 conversation = {} def connect_human(self,human): self.human_name = human.name self.chat_room.append(self.human_name) def connect_robot(self, robot): self.robot_name = ro...
class Person(object): def __init__(self, education, name): self. education = education self.name = name def work(self): print("%s goes to work." % self.name) print("%s has a %s education." % (self.name, self.education)) class Employee(Person): def __init__(self, education,...
import itertools def reachable_states(uso): """ Given a set of edges and a start state, return list of reachable states. """ reach = set([uso.start_state]) for i in range(uso.k - 1): reach.update(q2 for ((q1, a), (q2, b)) in uso.table.iteritems() if q1 in reach) return reach ...
#######################Happy Numbers########################## # # # square each digit, then add the results together # # repeat with new number until reduced to single digit # # if single digit is 1, then number is happy # ...
from collections import Counter from random import choice class hangman_solver: all_words = dict() #Sorted by length min_len = 3 max_len = 3 used_letters = set() #Set of letters that are not in the word pattern = [] game_over = False alphabet = set('abcdefghijklmnopqrstuvwxyz') def __in...
print("Welcome to Ivan Malkov's Naughts and Crosses!") gamemode=input( ''' Enter one of the following numbers in order to select its corresponding option 1 Tutorial 2 1 player 3 2 players : ''' ) if gamemode=="1": def tutorial(x) tutorial.gametutorial() if gamemode=="2": import sin...
x = 11 if x < 10: print ('less than ten') if x > 10: print ('greater than ten')
#!/usr/bin/env python3 from multiprocessing.pool import ThreadPool as Pool import matplotlib.pyplot as plt import subprocess as sp import platform import time import os class address_checker(): """This is a class to evaluate responsativity of multiple addresses to a ping and find addresses with same host b...
# Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. # There is only one majority number in the array. # O(n) time and O(k) extra space. class Solution: """ @param nums: A list of integers @param k: An integer @return: The m...
""" 406. 根据身高重建队列 假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对 (h, k) 表示,其中 h 是这个人的身高,k 是应该排在这个人前面且身高大于或等于 h 的人数。 例如:[5,2] 表示前面应该有 2 个身高大于等于 5 的人,而 [5,0] 表示前面不应该存在身高大于等于 5 的人。 编写一个算法,根据每个人的身高 h 重建这个队列,使之满足每个整数对 (h, k) 中对人数 k 的要求。 示例: 输入:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 输出:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 提示: ...
""" 19. 删除链表的倒数第N个节点 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明: 给定的 n 保证是有效的。 进阶: 你能尝试使用一趟扫描实现吗? """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class...