text
stringlengths
37
1.41M
import matplotlib import math m=int(raw_input("Enter the limit for RNG\n")); n=int(raw_input("How many numbers do you wish to generate?\n")); a=13;#multiplier c=17;#increment x=[]; frst_val=int(raw_input("Enter seed\n")); x.append(frst_val); for i in range(1,n): x.append((a*x[i-1]+c)%m); print "Numbers gen...
from pprint import pprint string = input("Введите 3 цифры через пробел: ") print("------------------------------------------------------------") array = string.split(" ") a = int(array[0]) b = int(array[1]) c = int(array[2]) sum = a + b + c multiply = a * b * c average = (a + b + c) / 3 print(f"{a}+{b}+{c} = {sum}"...
import PIL import requests def image_sizes(urls): """Compute image sizes at `urls` >>> url = 'https://bit.ly/2zp7YxL' >>> urls = [url]*2 """ sizes = [] for url in urls: # Download the Image data = requests.get(url, stream=True).raw img = PIL.Image.open(data) ...
N = 10 quantity = int(input()) if quantity > N: print("INVALID INPUT") else: print("Number of Candies Sold:",quantity) N = N - quantity print("Number of Candies available:",N)
import sys import subprocess import os import pygame def check_events(settings, screen): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: # solve puzzle and show in screen if event.key == pygame.K_SPACE: ...
# -*- coding: utf-8 -*- """ Created on Sun Oct 14 04:14:09 2018 @author: dp """ import random import time #import emoji secbreak = str('-' * 50) #create global variable for 'section breaks' #print(secbreak) class War: #Establish the War class with supporting attributes #generate random action variables ...
from random import * def main(): while True: try: n = int(input('Please enter the size of the matrix ')) except: print('Please provide a positive integer') continue a =[] top = 0 bottom ...
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """...
# author wukat ''' The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are b...
# author wukat ''' An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 x d10 x d...
# author wukat ''' The nth term of the sequence of triangle numbers is given by, tn = 1/2 n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. ...
"""Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110...
"""The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence (starting at 13 and finish...
#!/Users/anthonyquivers/anaconda3/bin/python #Date Started: 200325 def wordBoggle(board, words): def neighbors_of_pos(pos): yield((pos[0] - 1, pos[1] - 1)) yield((pos[0], pos[1] - 1)) yield((pos[0] + 1, pos[1] - 1)) yield((pos[0] - 1, pos[1])) yield((pos[0] + 1, pos[1])) ...
""" 113. Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Return: [ [5,4,11,2...
""" 206. Reverse Linked List Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ # Definition for singly-linked list. # class ListNode(object): # def...
""" 121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a s...
class Solution: def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]: nums = [] for i in nums1: if i in nums2 or i in nums3: nums.append(i) for j in nums2: if j in nums3 and j not in nums1: nums.app...
for i in range(5): squared = i * 2 print(squared) print("Done!")
dict1 ={1:'PArth',2:"Manan",3:"Jeet"} dict2={'key1':'value1','key2':'value2','key3':'value3','key4':'value4','key5':'value5'} dict3={'key1':1,2:'value2',"three":3.00,4.0:[1,2,3,4]} print( "dict1:",dict1) print("dict2:",dict2) print("dict3:",dict3) print(dict1.items()) print("dict1 1st value:",dict1[1]) #by [] operato...
f=open('filesample2.txt','r') print(f.readlines()) #f.readlines returns list of strings f.seek(0) print(list(f.read())) #f.read returns iterator of characters for line in open('filesample2.txt'): print(line.rstrip()) f.seek(0) for line in open('filesample2.txt'): print(line)
str=" I am Parth Maheshwari " print('printing 2nd index:', str[2]) print('printing 2-4 index by slicing operator:',str[2:4]) #starting and ending print('printing everything upto 10 :',str[:10]) print('printing negative -1 index:', str[-1]) print(str[3:]) print(str[3:8:2]) # starting and ending + step size print("Reve...
# filter(function name which returns boolean value, iterable) def evencheck(x): if x%2==0: return True else: return False print(evencheck(10)) p=filter(lambda x:x%2==0,range(1,11)) print(list(p)) # another example to find filter the list which is greater than 3 li=[1,2,4,3,100,2,6,34,6,7,4...
class Books(object): '''this is a class for creating books''' def __init__(self,author,name,pages): print("Book created:") self.author=author self.name=name self.pages=pages def __str__(self): return ("Title :{} \n Author :{} \n Total no pages: {}".format(self.name,s...
class Song: """Class to represent a song Attributes: title (str): The title of the song artist (Artist): An artist object representing the songs creator. duration (int): The duration of the song in seconds. May be zero """ def __init__(self,title,artist,duration...
s="Hello World of course.This is second line" print(s.capitalize()) print(s.upper()) print(s.lower()) print(s.count('o')) print(s.find('o')) print(s.center(40,'*')) #isalnum islpha print(s.islower()) print(s.isspace()) print(s.istitle()) print(s.split()) print(s.split('o')) print(s.split('o',1)) print(s.partition...
print("program to find prime nos between 1 to 100") num=2 while num<=100: f = True i = 2 while i<=num/2: if num%i==0: f=False break i+=1 if f==True: print(num) num+=1
class Personne: def __init__(self, nom, prenom): self.nom = nom self.prenom = prenom def getNom(self): return self.nom def getPrenom(self): return self.prenom class Auteur (Personne): oeuvre = [] def __init__(self, nom, prenom): super(...
x = 2 def Puissance(n): if n == 1: return x else: return x*Puissance(n-1) nombre = int(input('Renseignez un nombre entier : ')) print(Puissance(nombre))
import math def Cos(param1,param2, param3): try: if param1==None or param2 != '': if param3 == False: param1=math.cos(float(param2)) else: param1=math.cos(math.radians(float(param2))) else: if param3 == False: ...
#!/usr/bin/env python3 from abc import abstractmethod import cipher class Stream(cipher.AbstractBruteForceCipher): def applyPrf(self, plaintext, state): ciphertext = '' lowera = ord('a') for c in plaintext: (nextByte, state) = self.prf(state) ciphertext += chr(ord(c) ^ nextByte) return ciphertext ...
from urllib import robotparser from urllib.error import URLError def get_robots_parser(robots_url): ''' args: robots_url(str): url of website's robot.txt e.g http://www.a.com/robot.txt returns: rp (robotparser.RobotFileParser) ''' rp = robotparser.RobotFileParser() rp.set_url(robots_url) rp.read() return r...
numb = int(input("number inside: ")) for i in range(numb -1 ): print("x *",end = " ") print("x")
ships_sizes = [5, 7, 300, 90, 24, 50, 75 ] biggest = max (ships_sizes) print("hello, my name is hiep and there are my ship sizes: ") print(ships_sizes) print("now my biggest ship has size", biggest, "let's shear it") first_size = 8 ships_sizes[ships_sizes.index(biggest)] = first_size print("after shearing, here is ...
from turtle import * shape("classic") color("yellow") speed(-1) begin_fill() for i in range (4): forward(100) left(90) end_fill() mainloop()
#!/usr/bin/env python import fileinput from dataclasses import dataclass @dataclass class BoardingPass: row: int col: int seat: int def parse(input): return [boarding_pass(line[:-1]) for line in input] def boarding_pass(line): row = int(line[:7].replace("F", "0").replace("B", "1"), 2) col...
import pygame from .constants import BLACK, RED, GREEN, WHITE, BRONZE, DBRONZE, SQUARE_SIZE, ROWS, COLS from .piece import Piece class Board: def __init__(self): self.board = [] self.create_board() self.red_left = self.white_left = 15 # not necessary def draw_squares(self, win): ...
d = { 1 : 'apple', 2 : 'banana', 3 : 'orange' } d[4] = 'graph' # print(d[4]) #for key in d.keys(): # print(key) for key,value in d.items(): if key % 2 == 0: print(value)
yr=int(input("ENTER THE YEAR")) if (yr%4==0): print("THIS YEAR IS LEAP") else: print("THIS IS NOT A LEAP YEAR")
# Interleaving Strings # https://www.interviewbit.com/problems/interleaving-strings/ # # Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. # # Example, # Given: # # s1 = "aabcc", # s2 = "dbbca", # When s3 = "aadbbcbcac", return true. # When s3 = "aadbbbaccc", return false. # # Return 0 / 1 (...
# Intersection of Linked Lists # https://www.interviewbit.com/problems/intersection-of-linked-lists/ # # Write a program to find the node at which the intersection of two singly linked lists begins. # # For example, the following two linked lists: # # # A: a1 → a2 # ↘ # ...
# Sorted Array To Balanced BST # https://www.interviewbit.com/problems/sorted-array-to-balanced-bst/ # # Given an array where elements are sorted in ascending order, convert it to a height balanced BST. # # Balanced tree : a height-balanced binary tree is defined as a binary tree in which the depth of # the two subtre...
# Rain Water Trapped # https://www.interviewbit.com/problems/rain-water-trapped/ # # Given n non-negative integers representing an elevation map where the width of each bar is 1, # compute how much water it is able to trap after raining. # # Example : # # Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. # # Rain water trappe...
# Smallest sequence with given Primes # https://www.interviewbit.com/problems/smallest-sequence-with-given-primes/ # # Given three prime number(p1, p2, p3) and an integer k. Find the first(smallest) k integers which # have only p1, p2, p3 or a combination of them as their prime factors. # # Example: # # Input : # Prime...
# Edit Distance # https://www.interviewbit.com/problems/edit-distance/ # # Given two words A and B, find the minimum number of steps required to convert A to B. # (each operation is counted as 1 step.) # # You have the following 3 operations permitted on a word: # # Insert a character # Delete a character # Replace a c...
# Merge K Sorted Lists # https://www.interviewbit.com/problems/merge-k-sorted-lists/ # # Merge k sorted linked lists and return it as one sorted list. # # Example : # # 1 -> 10 -> 20 # 4 -> 11 -> 13 # 3 -> 8 -> 9 # will result in # # 1 -> 3 -> 4 -> 8 -> 9 -> 10 -> 11 -> 13 -> 20 # # # # # # # # # # # # # # # # # # # # ...
# Highest Product # https://www.interviewbit.com/problems/highest-product/ # # Given an array of integers, return the highest product possible by multiplying 3 numbers from the array # # Input: # # array of integers e.g {1, 2, 3} # NOTE: Solution will fit in a 32-bit signed integer # Example: # # [0, -1, 3, 100, 70, 5...
# Seats # https://www.interviewbit.com/problems/seats/ # # There is a row of seats. Assume that it contains N seats adjacent to each other. There # is a group of people who are already seated in that row randomly. i.e. some are sitting # together & some are scattered. # # An occupied seat is marked with a character 'x'...
# Hotel Bookings Possible # https://www.interviewbit.com/problems/hotel-bookings-possible/ # # A hotel manager has to process N advance bookings of rooms for the next season. His hotel has K rooms. # Bookings contain an arrival date and a departure date. He wants to find out whether there are enough rooms in # For exam...
# Tushar's Birthday Party # https://www.interviewbit.com/problems/tushars-birthday-party/ # # As it is Tushar’s Birthday on March 1st, he decided to throw a party to all his friends at TGI Fridays in Pune. # Given are the eating capacity of each friend, filling capacity of each dish and cost of each dish. A friend is #...
# Stepping Numbers # https://www.interviewbit.com/problems/stepping-numbers/ # # Given N and M find all stepping numbers in range N to M # # The stepping number: # # A number is called as a stepping number if the adjacent digits have a difference of 1. # e.g 123 is stepping number, but 358 is not a stepping number # # ...
# Search for a Range # https://www.interviewbit.com/problems/search-for-a-range/ # # Given a sorted array of integers, find the starting and ending position of a given target value. # # Your algorithm’s runtime complexity must be in the order of O(log n). # # If the target is not found in the array, return [-1, -1]. # ...
# Binary Tree From Inorder And Postorder # https://www.interviewbit.com/problems/binary-tree-from-inorder-and-postorder/ # # Given inorder and postorder traversal of a tree, construct the binary tree. # # Note: You may assume that duplicates do not exist in the tree. # Example : # # Input : # Inorder : [2, 1, ...
# Sorted Permutation Rank # https://www.interviewbit.com/problems/sorted-permutation-rank/ # # Given a string, find the rank of the string amongst its permutations sorted lexicographically. # Assume that no characters are repeated. # # Example : # # Input : 'acb' # Output : 2 # # The order permutations with letters 'a'...
# Path Sum # https://www.interviewbit.com/problems/path-sum/ # # Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that # adding up all the values along the path equals the given sum. # # Example : # # Given the below binary tree and sum = 22, # # 5 # / \ # ...
# Flip # https://www.interviewbit.com/problems/flip/ # # You are given a binary string(i.e. with characters 0 and 1) S consisting of characters # S1, S2, …, SN. In a single operation, you can choose two indices L and R such that # 1 ≤ L ≤ R ≤ N and flip the characters SL, SL+1, …, SR. By flipping, we mean change # char...
# 3 Sum # https://www.interviewbit.com/problems/3-sum/ # # Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. # Return the sum of the three integers. # # Assume that there will only be one solution # # Example: # given array S = {-1 2 1 -4}, # and target = 1...
# Remove Nth Node from List End # https://www.interviewbit.com/problems/remove-nth-node-from-list-end/ # # Given a linked list, remove the nth node from the end of list and return its head. # # For example, # Given linked list: 1->2->3->4->5, and n = 2. # After removing the second node from the end, the linked list bec...
# Word Ladder II # https://www.interviewbit.com/problems/word-ladder-ii/ # # Given two words (start and end), and a dictionary, find the shortest transformation sequence # from start to end, such that: # # Only one letter can be changed at a time # Each intermediate word must exist in the dictionary # #...
# Single Number II # https://www.interviewbit.com/problems/single-number-ii/ # # Given an array of integers, every element appears thrice except for one which occurs once. # # Find that element which does not appear thrice. # # Note: Your algorithm should have a linear runtime complexity. # # Could you implement it wit...
# Merge Two Sorted Lists # https://www.interviewbit.com/problems/merge-two-sorted-lists/ # # Merge two sorted linked lists and return it as a new list. # The new list should be made by splicing together the nodes of the first two lists, and should also be sorted. # # For example, given following linked lists : # # 5 ...
# Max Rectangle in Binary Matrix # https://www.interviewbit.com/problems/max-rectangle-in-binary-matrix/ # # Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area. # # Bonus if you can solve it in O(n^2) or less. # # Example : # # A : [ 1 1 1 # 0 1 ...
# Intersection Of Sorted Arrays # https://www.interviewbit.com/problems/intersection-of-sorted-arrays/ # # Find the intersection of two sorted arrays. # OR in other words, # Given 2 sorted arrays, find all the elements which occur in both the arrays. # # Example : # # Input : # A : [1 2 3 3 4 5 6] # B : [3 3 5]...
# Painter's Partition Problem # https://www.interviewbit.com/problems/painters-partition-problem/ # # You have to paint N boards of length {A0, A1, A2, A3 … AN-1}. There are K painters available # and you are also given how much time a painter takes to paint 1 unit of board. You have to get # this job done as soon as p...
# Equal Average Partition # https://www.interviewbit.com/problems/equal-average-partition/ # # Given an array with non negative numbers, divide the array into two parts such that the # average of both the parts is equal. # Return both parts (If exist). # If there is no solution. return an empty list. # # Example: # # #...
# Generate all Parentheses II # https://www.interviewbit.com/problems/generate-all-parentheses-ii/ # # Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n. # # For example, given n = 3, a solution set is: # # "((()))", "(()())", "(())()", "()(())", "()()(...
# Rotated Sorted Array Search # https://www.interviewbit.com/problems/rotated-sorted-array-search/ # # Suppose a sorted array is rotated at some pivot unknown to you beforehand. # # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ). # # You are given a target value to search. If found in the array, return its index, # ...
# Square Root of Integer # https://www.interviewbit.com/problems/square-root-of-integer/ # # Implement int sqrt(int x). # # Compute and return the square root of x. # # If x is not a perfect square, return floor(sqrt(x)) # # Example : # # Input : 11 # Output : 3 # # DO NOT USE SQRT FUNCTION FROM STANDARD LIBRARY # # # ...
# Subset # https://www.interviewbit.com/problems/subset/ # # Given a set of distinct integers, S, return all possible subsets. # # Note: # Elements in a subset must be in non-descending order. # The solution set must not contain duplicate subsets. # Also, the subsets should be sorted in ascending ( lexicographic ) ord...
from sys import argv import os if len(argv) < 3: print('Fatal: you forgot to enter an argument.') else: print('Argument exists') script, filename, second = argv print(argv) name = second if os.access(filename, os.F_OK): print('Given file path is exist.') else: print('No such file') txt = open(filena...
#импорт csv файла import csv # оглашение функции с параметром(csv_file)название параметраметра def clean_csv(csv_file): #открытие и чтение with open(filename, 'r') as csv_file: reader = csv.DictReader(csv_file,delimiter=',') result = [] for raw in reader: if len(raw['level']) != 0 : result.append(raw) ...
nam = input('Enter your name:') age = int(input('Enter the number:')) print (nam) print(age) f = (nam),(age) import csv with open('database.csv','a',newline='')as file: csv.writer(file).writerow(f)
#The code below reads in some important libraries from socketIO_client import SocketIO import serial import argparse #This code creates a parser #A parser is used to parse input's to your program #Recall you will be running your program as follows: #client.py --station station_number --port port_number #Your program t...
angle=0 x=0 def setup(): size(1500,1500) fullScreen() def draw(): global angle global x fill(random(200,255),random(200,255),random(200,255)) translate(width/2,height/2) rotate(radians(angle)) ellipse(x,0,90,50) ellipse(x,1500-200,50,50) ellipse(x,100,20,20) ...
DEBOUNCE_TIME = 0.005 # five milliseconds # DEBOUNCE_TIME = 1.000 import time ''' ######################################################## # Button Debouncer - will lag-lessly send buttonDown, # but will have a debounced buttonUp ######################################################## ''' class ButtonDebouncer(object...
#!/usr/bin/env python import click from random import randint from time import sleep def generate_elements(num_elements): return [randint(0,9) for x in range(num_elements)] def print_elements_in_row_and_wait(elements_to_print, wait_time): for x in elements_to_print: print("{} ".format(x), end='', flush=True) sl...
# CNN 모델에 대한 설명은 # https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/ 여기 참고 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev = 0.1) return tf.Variable(initial) # 완전연결계층(fully connect) 나 합성곱계층(convolution)의 가중치 지정 # stddev는 표준 편차로 작을 수록 평균값이랑 비슷 # Truncated 무작위로 초기화 시킴 # 상수로 초기화 하...
## Handle the exception thrown by the code below by using try and except blocks. try: for i in ['a','b','c']: print(i**2) except: print("Please enter a valid number") finally: print("This block will execute always") # Handle the exception thrown by the code below by using try and except blocks. Th...
##bootcamp file for practice inputStr = "Python for Beginners" print(inputStr.find("for")) ## will tell you the first index of 'for' print(inputStr.replace("for", "4")) ##will replace for by 4 in the inputStr myList = [2,4,6,8,10] print(myList[0]) print(myList[-1]) print(myList[0:3]) print(6 in myList) myList.insert...
def quickSort(alist, leftEnd, rightEnd): left = leftEnd right = rightEnd pivotPoint = (leftEnd+rightEnd)/2 pivot = alist[pivotPoint] while(left < right): while(alist[left] < pivot): left += 1 while(alist[right] > pivot): right -= 1 if(left <= right): ...
def gcd(m,n): while(n%m!=0): r=n%m n=m m=r return m print(gcd(48,36)) print(gcd(434,966))
#anagram is when the two stringss can be written using the exact same letters def anagram(s1,s2): s1=s1.replace(' ','').lower() s2=s2.replace(' ','').lower() return sorted(s1)==sorted(s2) print(anagram('dog','god')) print(anagram('my name is','Birhanu'))
'''this class holds the events information''' class Events: def __init__(self, event_id, event_date, venue): self.__event_id = event_id self.__event_date = event_date self.__venue = venue def set_event_id(self, event_id): self.__event_id = event_id def set_event_date(self...
import tensorflow as tf #from tensorflow.examples.tutorials.mnist import input_data from tensorflow.examples.tutorials.mnist import input_data mnist=input_data.read_data_sets("/tmp/data",one_hot=True) n_nodes_hll1=500 n_nodes_hll2=500 n_nodes_hll3=500 n_classes=10 batch_size=100 x=tf.placeholder('float'...
# ---------------------------------------------------------------------------------- # -- Engineer Name : Mugilvanan Vinayagam # -- Description : Python implementaton of conversion of floating point 32-bits # -- representation to 8 bit representation. # ----------------------------------------------...
count = 1 while count > 0 : print(count) count = count + 1 if count == 1001: break print( 'Woooohoooooo')
''' Задание №2. Длина Московской Кольцевой Автомобильной Дороги = 109 километров. Стартуем с нулевого километра МКАД и едем со скоростью V километров в час. На какой отметке остановимся через T часов? Программа получает на вход значение V и T. Если V > 0, то движемся в положительном направлении по МКАД. Если V < 0...
a=int(input()) #Method 1 # sq=0 # i=1 # while i*i<=a: # sq=i # i=i+1 # print(sq) #Method 2 sq=0 i=1 while i<=int(a/2): if int(a/i)==i: print(i) sq=1 break i=i+1 if sq==0: print("0")
n=int(input()) t=n for i in range(1,n+1,1): for j in range(t,1,-1): print("*",end=" ") t=t-1 print()
# -*- coding: utf-8 -*- """ Created on Fri Mar 9 18:26:03 2018 @author: narendra """ count = 0 while True: print(count) count += 1 if count >= 10: break
# -*- coding: utf-8 -*- """ Created on Fri Mar 9 00:08:51 2018 @author: narendra """ answer = "'Tis but a scratch!" def black_knight(): if answer == "'Tis but a scratch!": return True else: return False def french_soldier(): if answer == "Go away, or I shall taunt y...
# -*- coding: utf-8 -*- """ Created on Sun Mar 11 18:19:04 2018 @author: narendra """ to_one_hundred = range(101) # Add your code below! backwards_by_tens = to_one_hundred[::-10] print(backwards_by_tens)
# -*- coding: utf-8 -*- """ Created on Sun Mar 11 22:40:00 2018 @author: narendra """ class Shape(object): """Makes shapes!""" def __init__(self, number_of_sides): self.number_of_sides = number_of_sides # Add your Triangle class below! class Triangle(Shape): def __init__(self,side1,side2,side3): self.s...
# -*- coding: utf-8 -*- """ Created on Thu Mar 8 23:16:56 2018 @author: narendra """ from datetime import datetime now=datetime.now() print(now.year) print(now.month) print(now.day)
# -*- coding: utf-8 -*- """ Created on Fri Mar 9 15:23:13 2018 @author: narendra """ n = [3, 5, 7] def total(number): result=0 for item in number: result+=item return result print(total(n))
# -*- coding: utf-8 -*- # @Time : 2020/4/4 22:06 # @Author : WuxieYaYa """ 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。 示例: 输入: [0,1,0,2,1,0,1,3,2,1,2,1] 输出: 6 链接:https://leetcode-cn.com/problems/trapping-rain-water """...
# -*- coding: utf-8 -*- # @Time : 2020/3/16 21:51 # @Author : WuxieYaYa """ 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。   示例: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] 给定 word = "ABCCED", 返回 true 给定 word = "SEE", 返回 true ...
# -*- coding: utf-8 -*- # @Time : 2020/3/23 12:05 # @Author : WuxieYaYa """ 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。 示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2 示例 2: 输入: haystack = "aaaaa", needle = "bba" 输出: -1 说明: 当 needle 是空字符串时,我们应当返回...
# -*- coding: utf-8 -*- # @Time : 2020/4/26 10:56 # @Author : WuxieYaYa """ 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [   1->4->5,   1->3->4,   2->6 ] 输出: 1->1->2->3->4->4->5->6 链接:https://leetcode-cn.com/problems/merge-k-sorted-lists """ from queue import PriorityQueue import heapq class ListNode: def _...
# -*- coding: utf-8 -*- # @Time : 2020/11/9 13:43 # @Author : WuxieYaYa 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 def preorder_traversal(root: Tree...