text
stringlengths
37
1.41M
lista = [] cont = 1 print("LISTA COM 5 ELEMENTOS") while cont <= 5: num = int(input(f"Digite o {cont}ª número: ")) lista.append(num) cont = cont + 1 print(f"LISTA: {lista}") while True: print("""OPÇÕES [1] PARA ADICIONAR UM ELEMENTO NA LISTA [2] PARA ADICIONAR ELEMENTO NA POSIÇÃO DESE...
lista = [] num = int(input("Digite quantos números você quer adicionar na lista: ")) cont = 0 while cont < num: v = int(input(f"Digite um valor para a posição {cont}: ")) lista.append(v) if cont == 0: maior = lista[cont] menor = lista[cont] else: if lista[cont] > maior:...
''' This file demonstrates at a high-level what your program should do. It does not support the debug option. Note that the data structures used in this version are significantly different than the data structures you will use in your version. This version uses a dictionary of arrays. You will use a binary tree of qu...
dict2={} dict1 = {} dict3={} dict4={} n = int(input("Enter the number of dictionary in dict1: ")) p = int(input("Enter the number of dictionary in dict2: ")) q = int(input("Enter the number of dictionary in dict3: ")) for i in range(n): k = int(input("Enter the key: ")) v = int(input("Enter the value: ")) d...
array1 = input("Enter the first array: ") sp_list1 = array1.split() for i in range(0, len(sp_list1)): sp_list1[i] = int(sp_list1[i]) print(sp_list1) array2 = input("Enter second array: ") sp_list2 = array2.split() for i in range(0, len(sp_list2)): sp_list2[i] = int(sp_list2[i]) print(sp_list2) result = list(set...
t = input("Enter tuple elements: ") a = tuple((x) for x in t.split()) search_ele = input("Search index of: ") rem = a.index(search_ele) print(f"Index[{search_ele}] is {rem}")
a = int(input("Enter the start_of_range: ")) b = int(input("Enter the end_of_range: ")) n = int(input("Enter the number: ")) if n in range(a, b): print(f"{n} is in range {a,b}") else: print(f"{n} is out of range {a,b}")
s1 = int(input("Enter a string :")) def fun(s1): slice_s1 = slice(-1) return s1[slice_s1] print(fun(s1))
import operator str = input("Enter a string: ") d = {} for x in str: if x in d.keys(): d[x]+= 1 else: d[x] = 1 print(dict(sorted(d.items(), key=operator.itemgetter(1), reverse=True)))
def mid_string(str1, str2): length = int(len(str1)/2) print(str1[:length] + str2 + str1[length:]) print(mid_string(input("string1: "),input("string2: ")))
import unittest import parser as parse class UnitTesting(unittest.TestCase): parser = parse.Parser() def test_basic_usage(self): self.parser.add_argument('--key', True, 'integer') self.parser.add_argument('--name', False, 'string') command_line_parameters = ['./test', '--key=1234', '--...
# ---------------------------------------------------------------- # # Algorithme Astar 1.0 # -> Je n'ai pas encore testé sur les graphes du prof # Si vous avez des idées d'optimisation c'est tout benef. # ---------------------------------------------------------------- infty = 10**15 ...
import random random.randrange(0, 100) number = random.randrange(0, 100) Running = True while Running: guess = int(input('Insert your number.')) if guess == number: print('Gotcha!') Running = False elif number > guess: print('Guessed number is more than you have written.') el...
import logging class Chapter: def __init__(self, chars, start, end): """ :param chars: total count of characters in all this chapter's paragraphs :param start: index of the book's paragraphs which is the FIRST in this chapter :param end: index of the book's paragraphs which is be t...
""" Cribbage2 Erica Chesley https://github.com/ericachesley/cribbage2 Cribbage game program written for Hackbright Academy Phenomenal Women Scholarship application. Run from main.py; see README.txt for more information. """ import time from constants import PRINT_SPEED class Player: def __init__(sel...
def char_count(text): """ counts the number of occurances of ascii characters - ord(ch)<128, in a text. Returns a dictionary, with keys being the observed characters, values being the counts """ d = {} for ch in text: if ord(ch)>=128: continue if ch in d: d[ch] = 1+d[ch]...
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello, world!" # turn a route into a template for a generalized set of routes # allowing any route and passing it as a string variable @app.route("/<string:name>") # anything typed after the slash will be saved as a string "name"...
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Flight(db.Model): __tablename__ = "flights" id = db.Column(db.Integer, primary_key=True) origin = db.Column(db.String, nullable=False) destination = db.Column(db.String, nullable=False) duration = db.Column(db.Integer, nullable=False)...
#https://www.hackerrank.com/challenges/introduction-to-regex import re exp1 = r'\+*[0-9]*\.[0-9]+' exp2 = r'\-*[0-9]*\.[0-9]+' a = int(input()) z = [input() for i in range(a)] for i in z: print (True if re.fullmatch(exp1, i) or re.fullmatch(exp2, i) else False)
import turtle t = turtle.Turtle() t.shape("turtle") s = turtle.textinput("","도형을 입력하시오:") if s == "사각형": s = turtle.textinput("","가로:") w = int(s) s = turtle.textinput("","세로:") h = int(s) t.forward(w) t.left(90) t.forward(h) t.left(90) t.forward(w) t.left(90) ...
# import os # from collections import namedtuple # # simplest way to read file line by line # def cast_data_type(data_type, value): # if data_type == "DOUBLE": # return float(value) # elif data_type == "INT": # return int(value) # else: # return str(value) # def cast_row(data_type...
from math import factorial # class FactorialIterator: # def __init__(self, upper_limit): # self._upper_limit = upper_limit # self._idx = 0 # def __iter__(self): # return self # def __next__(self): # if self._idx >= self._upper_limit: # raise StopIteration # ...
def break_string(isstring): upper = [] lower = [] digit = [] others = [] for char in isstring: if char.isupper(): upper.append(char) elif char.islower(): lower.append(char) elif char.isdigit(): digit.append(char) elif c...
#Settings CODE import json #First, we write some codes in bash in order to filter the json files for the criterias we were looking for, #which are entries that contain the string 'dutch', 'birthYear', and 'deathYear', excluding entries containing #containing the string 'fictional', and 'mythology'. #khoatran@MacBo...
#------------------------- 10% ------------------------------------- # The operand stack: define the operand stack and its operations opstack = [] #assuming top of the stack is the end of the list # Now define the HELPER FUNCTIONS to push and pop values on the opstack # Remember that there is a Postscript operator c...
#from the calculator import calculator class, files should be in the same directory from calculator import Calculator import os os.chdir('D://DBS//5.Programming_for_big_data//github//pz_pbd//CA5') # testing method by which individual units of source code import unittest class Testcalculator(unittest.TestCase): #...
import streamlit as st import pandas as pd import numpy as np import random import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go import altair as alt import pydeck as pdk URL = "https://data.cityofnewyork.us/api/views/h9gi-nx95/rows.csv?accessType=DOWNLOAD" # URL = "~...
import calculator import countoff import rockpaperscissors import compoundInterestCalculator import tictactoe #route user to chosen project def select(selection): #route to calculator if selection == '1': calculator.main() print() main() #route to compound interest calculator e...
#4.Write a Python program to read specific columns of a given CSV file and print the content of the columns. import csv with open('D:\depart.csv', newline='') as csvfile: data = csv.DictReader(csvfile) print("ID Department Name") print("---------------------------------") for row in data: print(row['dep...
def minDistance(nums,min , max): n = len(nums) print(min,max) dist=999999999 # Initializing a big value for the distance if min==max: return 1 else: for i in range(n): for k in range(i+1, n): if (min ==nums[i]and max== nums[k] or max==nums[i] and min...
name = input("What is your name - ") print (name) full_name = input("What is your full name - ") age = input("Your age - ") print("Full name is " + full_name) print("Your age is " + age)
name = "Amir"; age = "27"; print("Hello there My name is Amir,") print("I am 27 years old.") print("Hi there My name is " + name + ",") print("I am " + age + " years old.") string_name="Amir" a = 45 f =- 2.3356 is_male = True is_female = False
file = open("File_Test.txt", "+r") # here r is read mode, also w as write, a as append, r+ as both read and write print(file.writable()) # this checks whether it is writable print(file.readable()) # this checks whether it is readable print("\n") '''print(file.read()) ...
''' monthly_names = { "Jan": "January", # here Jan is a key and January is a value of both the string type "Feb": "February", "Mar": "March", "Apr": "April", } print(monthly_names) print(monthly_names["Feb"]) print(monthly_names.get("Feb")) # both of them are same, both ...
# Write a program to find the n-th ugly number. # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # Example: # Input: n = 10 # Output: 12 # Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. # Note: # 1 is typically treated as an ugly number. # n...
# https://www.hackerrank.com/challenges/nested-list/problem def sortScore(obj): return obj[1], obj[0] if __name__ == '__main__': arr = [] for _ in range(int(input())): name = input() score = float(input()) arr.append([name, score]) arr.sort(key=sortScore) minScore = mi...
""" Orienteer.py: classes for computing a appromiate solution to the orienteering problem using genetic algorithm Mark Lubin """ RADIUS = 6368 #radius of earth in kilometers import Location,random,time,walkerRandom from math import acos,sin,cos,radians,ceil class OrienteeringProblem: def __init__(self,locatio...
""" This file holds functions to import and merge in weather data.""" import pandas as pd import numpy as np from math import sin, cos, sqrt, atan2, radians from io import BytesIO import boto3 def get_weather_as_df(keys): """ Use keys to import all weather csvs, downloaded from national weather association ...
#Who's_your_Daddy.py #Joe Carty #11/12/14 import pickle choice = () names = {"Charlie":"Timmy","Dennis":"Will","Mac":"Billy","Frank":"Danny"} while choice != '0': print( ''' Who's Your Daddy? ================= 0 - Quit 1 - Find out who's your dad 2 - Add a daddy 3 - Delete a dad =======...
def fib(n): print 'n=',n if n>1: return n*fib(n-1) else: print 'end of the line' return 1
import sys import json import time """ A function to truncate a float to "n" digits without rounding f: The float to be truncated n: Number of decimal points to maintain source: http://stackoverflow.com/questions/783897/truncating-floats-in-python @author: Madhavi Deshmukh """ def truncate(f, n): ...
## select kth smallest element # from quick_sort import partition import random def selection(arr, k, start=0, end=None): if end == None: end = len(arr)-1 if end <= start: return while True: index = partition(arr, start, end) if k == index: break elif k...
## has logical bugs def sortColors(n): i, j = 0, len(n)-1 curr = 0 while curr < len(n): if color(n[curr]) == 'b': swap(n, i, curr) i += 1 elif color(n[curr]) == 'r': swap(n, j, curr) j -= 1 curr += 1 return n def swap(n, a, b)...
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def merge(left, right): lc, rc = 0, 0 merged = [None] * (len(left) + len(right)) while lc < len(left) and rc < len(right)...
# compare strings conform ASCII table print('a' > 'b') print('a' > 'c') print('c' > '9') # ASCII table print('ASCII | Char') for i in range(33,123): print('%d | %s' % (i,chr(i))) #iterate a string with enumerate - return a dict for k,v in enumerate('Interando String'): print('%d : %s ' %(k,v), end='\t')
# Z tego względu, że nie pamiętałem dokładnie treści zadania o jakim było wspomniane na ostatnich zdalnych e-lekcjach a klasa wiedziała, # że chodzi głównie tylko o "zgadywanie liczb" a nie jest to jakiś bardzo skomplikowany temat to nie zawracałem Panu głowy o szczegóły zadania # (czy koputer pyta, czy użytkownik, pr...
import tkinter as tk from tkinter import filedialog from lib import get_dist, get_importance, get_relevant, get_meaningfulness class Program(tk.Frame): def __init__(self, master): super().__init__() self.difficulty = 1/2 self.word_ranks = get_importance() #'print' analogy se...
#Prompt user to enter a start path and file name, search recursively for the given #file name starting at the given path, when file is found, #display the full path to the file. import os path=input("enter the path:") filename=input("enter Filename:") full_path=[] for r,d,f in os.walk(path): if filename in f: ...
#!/usr/bin/python from sys import argv import pygame from pygame.locals import * from maze import Maze class Game: def __init__(self, diff, dim, path): self.size = (800,600) self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption('Maze Demo') font = pygame.font.SysFont(pygame.fo...
n=int(input("Enter a range")) for i in range(1,n+1): if (i%3==0 and i%5==0): print(i,"= FizzBuzz") else: if(i%3==0): print(i,"= Fizz") elif(i%5==0): print(i,"= Buzz") else: print(i)
from unittest import TestCase class TestWindow(TestCase): def test_addition(self): a= float(input()) b= float(input()) c= a+b print("Addition should be : "+str(c)) return self.assertEqual((a+b),c) def test_subtraction(self): a = float(input()) b = float(...
num = float(input("输入一个数字: ")) if num > 0: print("大于0") elif num == 0: print('{"msg":"账户被禁, 可联系在线客服 处理","code":1,"obj":null,"datas":null,"attributes":null,"ext1":"/user/home"}') else: print("负数")
""" 需求: 如果年龄小于18,为童工,不合法 如果年龄18-60之间,为合法工作年龄 如果年龄大于60为退休年龄 """ """ 步骤: 1.用户输入自己的年龄,保存变量 --str 2.if做判断,elif 3.输出提示信息:您输入的年龄是x,合法与否 """ age=int(input("请输入您的年龄:")) if age<18: print(f"您的年龄为{age},童工") elif age>=18 and age<=60: print(f"您的年龄是{age},为合法工作年龄") else: print(f"您的年龄是{age},属...
"""" print("hello") ##基本语法 1.在python中严格区分大小写 2.python中的每一行就是一条语句,每条语句以换行结束 3.python中每一行语句不要过长(规范中建议每行不要超过80字符) “rulers”:【80】, 4.一条语句可以多行编写,语句后以\结尾 5.在python中使用#号来注释,注释的内容将会被解释器所忽略 我们可以通过注释对程序进行解释说明,一定要养成良好的编写注释的习惯 注释要求简单明了,一般习惯上#后边会跟着一个空格 ##自面量和变量 字面量就是一个一个的值,比如:1.1224145,,44...
#4 basamaklı palindromik sayilari bastitir for sayi in range(1000,10000): sayi_str=str(sayi) if sayi_str[::1]==sayi_str[::-1]: print(sayi,end=" ")
import math def findpermut(target, nums): print ". Target: %d" % (target) print ". Choices: %s" % (str(nums)) if len(nums) > 1: part = (target) / math.factorial(len(nums)-1) print ". Part: %d" %(part) first = nums[int(target / math.factorial(len(nums)-1))] print ". First: ...
# Find the largest prime factor of a composite number. if __name__ == '__main__': number = 600851475143 maxfactor = -1 # Try dividing with every possible factor factors until we reach the largest one # Dumb solution but takes less than 0.1 seconds to complete for factor in xrange(2, number/2)...
from fractions import Fraction def fraccomp(nu1, de1, nus2, des2): return Fraction(nu1, de1) == Fraction(int(nus2), int(des2)) if __name__ == '__main__': result = Fraction(1,1) for de in range(10, 100): des = str(de) for nu in range(10, de): nus = str(nu) if nus...
if __name__ == '__main__': limit = 1000 num = 3 den = 2 result = 0 for _ in xrange(1, limit): #print ". Fraction = %d/%d" % (num, den) if len(str(num)) > len(str(den)): result += 1 num, den = num + 2*den, den + num print "RESULT=%d" % (result)
# -*- coding: utf-8 -*- """ Created on Mon Jul 8 23:43:30 2019 @author: Marco """ def lengthOfLastWord(s): if len(s.split()) == 0: return 0 else: return len(s.split()[-1])
import RPi.GPIO as GPIO import random GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.OUT) GPIO.setup(3, GPIO.OUT) GPIO.setup(4, GPIO.OUT) GPIO.setup(17, GPIO.OUT) print ("Logic Gate Simulation") def AND (a,b): if a == 1 : if b == 1: return 1 else: return 0 def NAND (a,b): if AND(...
""" Goal: Create code to allow a user to create a shopping list Minimum requirements: * User can enter items which will be stored in the shopping list * User can exit item entry mode, which will cause the program to print the contents of the list Stretch goals: * User can delete an item from the list * A comman...
numbers = [2, 3, 6, 1, 2, 5, 1, 4, 3, 5] uniques = [] for number in numbers: if number not in uniques: uniques.append(number) print(uniques)
''' Task: Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the fu...
import numpy import math import operator # Methods common to both the transmitter and receiver. def hamming(s1,s2): # Given two binary vectors s1 and s2 (possibly of different # lengths), first truncate the longer vector (to equalize # the vector lengths) and then find the hamming distance #...
import random print("Number Guessing Game") number = random.randint(1, 9) chances = 0 while chances < 5: guess = int(input("Enter your number: ")) if guess == number: print("Congratulations! Your guess is right.") break elif guess < number: print("Your guess is ...
import MemoryGame import GuessGame import CurrencyRouletteGame import Score def welcome(name): return "\nHello" + name + " and welcome to the world of Games (WoG). \nHere you can findmany cool games to play\n" def load_game(): global result no_exception = False while no_exception == Fal...
# -*- coding: utf-8 -*- """ Created on Mon May 14 12:28:35 2018 @author: Peeyuh goyal """ str1=raw_input() l1= list(str1) letter=0 digit=0 for a in l1: if a.isdigit(): digit+=1 else: letter+=1 print "digit",digit print "letter",letter
# -*- coding: utf-8 -*- """ Created on Fri May 11 11:30:40 2018 @author: Peeyuh goyal """ str1=raw_input() str1=str1.strip() a=str1.find(" ") print(str1[a+1::]+" "+str1[:a+1:])
# Find nth even number in a given n number def fibonacciNumbers(n): fibNum = [] if n == 0 or n == 1: return n fibNum.append(0) fibNum.append(1) while n >= 2: fib = fibNum[-1] + fibNum[-2] fibNum.append(fib) n -= 1 return fibNum def nthevenFib(fibSeries, nthEven): res = fibonacciNumbers(fibSeries) even...
class Employee: employee_count = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = self.first + self.last + "@gmail.com" Employee.employee_count += 1 def emp_name(self): return "Employee name is: {} {}".format(self.first, sel...
class Employees: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary def __repr__(self): return "({}, {}, ${})".format(self.name, self.age, self.salary) e1 = Employees('Sindhu', 27, 100000) e2 = Employees('Hemanth', 29, 150000) e3 = Employees('Likith', 24, 90000) em...
input = """ 1 5""" import sys num_tests = int(sys.stdin.readline()) for i in range(num_tests): n = int(sys.stdin.readline()) sum = n * (n + 1) / 2 print sum output = """ 15"""
def firstAndLastOccurance(numbers): d = {} i = 0 for num in numbers: if not num in d: d[num] = [i] else: d[num].append(i) i += 1 for key, values in d.items(): print ("first occurance = %d and last occurance = %d" % (values[0], values.pop())) firs...
#! /usr/bin/python def factorial(n): fact = 1 if(n == 0): return 1 for i in range(1, n+1): fact *= i return fact def factorialRecursion(n): fact = 1 if(n == 0 or n == 1): return 1 else: return n * factorialRecursion(n-1) def main(): while(True): x = raw_input('Enter the number to ...
#Convert given digit into words def getDigits(num): l = [] i = 0 while num: digit = num % 10 num = int(num / 10) l.append((digit, i+1)) i += 1 return l[::-1] def convertToWords(arr): ones = {1: "one", 2: "two", 3: "three", 4: "four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9:"nine"} tens ...
num = int (input ("Enter the number ")) result = 0 for i in range (num + 1): result += i print (result)
import math def smallest_devisible_by_all(below=10): i = below stop = math.factorial(below) test = range(1, below) while i < stop: if all(i % x == 0 for x in test): return i i += below raise Exception(u"Impossibru!") if __name__ == '__main__': print smallest_devisible_by_all(20)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 26 00:24:30 2020 @author: joscelynec """ ''' Backtracking Algorithm to solve the N-Queens Puzzle Adapted from https://github.com/mattcollier/diagonals#sample-output ''' #Ultility displays the grid def printGrid(): global grid for i in rang...
word = 'banana' counter = 0 index = 0 for letter in word: if letter == 'a': counter = counter + 1 print(counter) def counter(w, c, index): counter = 0 index = index for letter in w: if letter == c: counter = counter + 1 print(counter) print('') counter('apple', 'a', 0)
def histogram(s): ''' count how many times each letter appear in string s''' d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] = d[c] + 1 return d def histogram_(s): ''' using get() to write concise code: get(key, default) return values of the key (return default in case key does not exist)'...
def backword(s): ''' take a stirng as an arg and displays letters backword''' length = len(s) for i in range(length): print(s[length-1-i]) backword("Python") ''' n o h t y P '''
# set n = 100 import turtle import math #turtle.Turtle create a Turtle object and assign it to a variable named bob bob = turtle.Turtle() print(bob) def polygon(t, length, n): for i in range(n): t.fd(length) t.lt(360/n) # length * n = circumference = 2*pi*r def circle(t, r): polygon(t,(2*math.pi*r)/100, 10...
''' most list methods are void: they modify the list and return None. t = t.sort() incorrect''' t = ['e','a', 'b', 'c'] print(t) t.append('d') print(t) t.sort() print(t) ''' ['e', 'a', 'b', 'c'] ['e', 'a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd', 'e'] '''
from ch.aplu.turtle import * ann = Turtle() ann.setPenColor("red") #square ann.forward(100) ann.right(90) ann.forward(100) ann.right(90) ann.forward(100) ann.right(90) ann.forward(100) #triangle ann.setPenColor("blue") ann.forward(100) ann.right(120) ann.forward(100) ann.right(120) ann.forward(10...
quiz = { "What is the name of Hiccup's Night Fury dragon?": "Toothless", "Which country won the Thomas Cup in 2014?": "Japan", "Who is the soulmate of Barbie?": "Ken", "How many countries are there in South East Asia (in numbers)?": ...
quiz = { "What is Python?": "A programming language", "Who is called the Father of Computer Science?": "Alan Turing", "Who is the current president of the US?": "Barack Obama", "In which country was Albert Einstein born?": "Germany"...
from math import * X= float(raw_input("digite o valor da coordenado do eixo X: "))#4010210.546#km Y=float(raw_input("digite o valor da coordenado do eixo Y: "))#-4260166.288#km Z=float(raw_input("digite o valor da coordenado do eixo Z: "))#-2533008.133 #km E=0.00669454185 a=6378160 #km lambida= (atan(Y/X))*(180/pi)# ...
# -*- coding: utf-8 -*- """ Created on Fri Jun 5 03:22:17 2020 @author: Matthew Davids """ import importlib mName = input('DNA input:') importlib.import_module(mName) inputfile = "DNA.txt" with open(inputfile,mode='r') as f: # using this way allows me not to worry about closing the file and also resetin...
#!/usr/bin/env python """ coding=utf-8 Build model for a dataset by identifying type of column along with its respective parameters. """ from __future__ import print_function from __future__ import division def is_in_range(x, config): """ Checks to see x is in the range of the config. :param x: number ...
""" Numerical integration. """ def next_step(a, b, h): x = a + h while x < (b - h): yield x x = x + h def trapezoidal(left, right, steps): """ Trapezoidal Rule: int(f) = h/2 * (f1 + 2f2 + ... + fn) :param left: left end of searching range :param right: right end of searching ...
""" Program to Print all Numbers in a Range Divisible by a Given Number """ n1=int(input("Enter the smallest number in range")) n2=int(input("Enter the highest number in range ")) n=int(input("Enter the number to be divided by:")) for i in range(n1,n2+1): if(i%n)==0: print(i)
print("Hello there") user_input=input('What is your name?') print('Hi {}'.format(user_input))
a = 7823 # this is a global variable, which is accessible anywhere def corn(): print(a) b = 3287 print(b) # variable declared inside a funcion def funge(): print(a) #print(b) # we can't use this variable 'b' anywhere else but the function 'corn()' corn() funge()
""" 给定一个没有重复数字的序列,返回其所有可能的全排列。 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] """ # 解答:用递归进行,每次交换两个元素,使得能返回所有的全排列 class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] sel...
""" 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / \ 1 3 输出: true 示例 2: 输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。 """ # 利用二叉搜索树中序遍历为升序的特性来做,先递归中序遍历,然后判断是否为升序 # D...
""" 实现一个基本的计算器来计算一个简单的字符串表达式的值。 字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格  。 示例 1: 输入: "1 + 1" 输出: 2 示例 2: 输入: " 2-1 + 2 " 输出: 3 示例 3: 输入: "(1+(4+5+2)-3)+(6+8)" 输出: 23 说明: 你可以假设所给定的表达式都是有效的。 请不要使用内置的库函数 eval。 """ # 解答:维护一个数字栈一个符号栈,遇到数字则遍历到不是数字后将其加入数字栈, 遇到符号则先判断符号栈有无符号,有的话则弹出两个数字和符号进行运算 # 遇到右括号则一直运算到左括号为止 class S...
""" 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 示例 1: 输入: 2.00000, 10 输出: 1024.00000 示例 2: 输入: 2.10000, 3 输出: 9.26100 示例 3: 输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25 说明: -100.0 < x < 100.0 n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 """ # 解答:直接用乘法会超时。所以用递归进行二分,把每次的n分成n/2的相乘形式,奇数就多乘一个x class Solution: def myPow(sel...
""" 给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。 示例: 假设 words = ["practice", "makes", "perfect", "coding", "makes"] 输入: word1 = “coding”, word2 = “practice” 输出: 3 输入: word1 = "makes", word2 = "coding" 输出: 1 注意: 你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。 """ # 解答:分别记录word1和word2最近一次的索引,并和结果比较看距离是否更短,更短则更新 clas...
""" 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 你应当保留两个分区中每个节点的初始相对位置。 示例: 输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5 """ # 解答:可以创建两个指针,分布将小于x的和大于、等于x的串起来,最后再首尾相连 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None cla...